Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript type narrowing too strict when using class method to update property

Tags:

typescript

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'")
    }
})();
like image 475
Sharpiro Avatar asked Apr 05 '26 17:04

Sharpiro


1 Answers

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

like image 133
Titian Cernicova-Dragomir Avatar answered Apr 08 '26 05:04

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!