#TS2564: Property X has no initializer and is not definitely assigned in the constructor.

4 messages · Page 1 of 1 (latest)

meager ore
#

Hi, can somebody guide me with the following error?

TS2564: Property dom has no initializer and is not definitely assigned in the constructor.

This is my code:

class App {
    public width = window.innerWidth;
    public height = window.innerHeight;

    public dom: HTMLDivElement;
    // ...

    constructor() {
        this.initDom(); // <-- it definitely is assigned in the constructor, albeit indirectly through this.
        // ...
    }

    private initDom() {
        this.dom = document.querySelector('#app') as HTMLDivElement;

        if (!this.dom) throw new ReferenceError('Cannot find DOM target.');
    }
    
    // ...
}

I can circumvent the error by changing

public dom: HTMLDivElement;

to

public dom: HTMLDivElement;

but note that I have several more properties and it feels wrong to do this for each one of them.

I have several initX functions and thought this was a nice solution to declutter the constructor. If I were to get rid of the separate methods and write all my init code in the constructor, I do not get this error.

This looks like a shortcoming of TypeScript.

spring goblet
#

@meager ore Yeah, TS does not do full source analysis of everything that you call in the constructor to determine if things are initialized.

#

Probably the simplest change you could make is;

constructor() {
    this.dom = this.initDom();
}

and have initDom return the value you want to set, rather than assign it.

meager ore
#

Ah, clever! Thank you, @spring goblet .