Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors?
In this example (run), this.x
is accessed in the method initY
before it's initialized in the constructor:
class A {
readonly x: number
readonly y: number
constructor(x: number){
this.y = this.initY() // this.x not initialized yet
this.x = x
}
private initY(): number {
return this.x + 1
}
}
console.log(new A(1).y) // prints: NaN
The solution I found involved using a static method or top-level function for initialization.
Any other more concise ideas? Can the compiler (already in strict mode) or linter catch these issues?