Creating a class like:
class myProps {
public readonly val1: boolean;
constructor(val1?: boolean) {
val1 != undefined ? this.val1 = val1 : val1 = true;
}
}
I would expect that his is ok, as inside the constructor (unlike the error claims) val1 is always set to a value. however I get this error (inside the IDE) on the readonly attribute val1:
Property ‘val1’ has no initializer and is not definitely assigned in
the constructor.
Why is this and how would I fix it correctly?
>Solution :
You are missing a this before your second assignment of val1, so you’re assigning to the local variable in the other branch, not the instance variable, hence the error that it is not always initialized. It should be
class myProps {
public readonly val1: boolean;
constructor(val1?: boolean) {
val1 != undefined ? this.val1 = val1 : this.val1 = true;
}
}