Is it intended that Typescript should be so strict on type narrowing when using a class method to update a property? I'm not saying Typescript should somehow analyze what a method is doing, but it is a regular practice for class instance properties to be modified by methods.
I understand that changing currentChar from a normal property or a property getter to a method would solve this, but I think properties and getters are very valuable.
Stackblitz
export class Parser {
data = "abcdefg"
currentIndex = 0
get currentChar(): string {
return this.data[this.currentIndex]
}
nextChar(): void {
++this.currentIndex
}
}
(() => {
const parser = new Parser()
if (parser.currentChar !== "a") {
return
}
const aChar: "a" = parser.currentChar // = type 'a', value 'a'
parser.nextChar()
const bChar: "a" = parser.currentChar // = type 'a', value 'b'
if (parser.currentChar === "b") { // Error: This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.
console.log("current char really equals 'b'")
}
})();
This is a limitation of control flow analysis. Since you check the class property the type of the property will be narrowed by the check, and typescript will not clear this narrowing when a method is invoked.
You can read more about this here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With