TypeScript Version: 2.1.4
Code
class blah {
private readonly _something = false;
constructor() {
this._something = true;
}
}
Expected behavior:
Doesn't cause an error
Actual behavior:
Causes an error
class blah {
private readonly _something: boolean;
constructor() {
this._something = true;
}
}
The type inferred for a const variable or readonly property without a type annotation is the type of the initializer as-is.
I guess "by design" is an answer. Not an answer I'd expect for this, but fair enough.
Can I ask why there are two initializers for _something ?
Because _something has a default value, and only some paths in the initializer set it. It was an easy fix to change it to "private readonly _something: boolean = false", it just seems an odd language construct. Readonly is only readonly after the end of the constructor. If anything, it feels like you should take the type as the union of all options set in the validity period, so in this case would be false|true.
This has already been discussed in https://github.com/Microsoft/TypeScript/issues/12189 in the context of https://github.com/Microsoft/TypeScript/issues/12148. The conclusion then was that this code is ambiguous, and the property should have a type annotation. in the absence of a type annotation, the compiler will use the type from the internalizer, i.e. false in this case.
Duplicate of #12148.
Most helpful comment
10676