typescript compiler erroneously complains that 'condition will always return true' when an accessor is used in the condition

Viewed 82

I experimented with typescript getter/setter accessors when I found what looks to me like a typescript compiler bug. Apparently the compiler doesn't treat accessors as method calls when statically evaluating conditions. The result is that it complains about the condition being always true when it clearly will not be always true.

The following code demonstrate the problem:

class BuggyCompiler {
    text: string = 'The fox jumps over the lazy dog';
    private position: number = 0;

    private get current(): string {
        return this.text[this.position];
    }

    test(): void {
        if ('[' !== this.current)
            return;
        ++this.position;

        // This condition will always return 'true' since the types
        // '"]"' and '"["' have no overlap.(2367)
        //  ~~~~~~~~~~~~~~~~~~~~~
        if (']' !== this.current)
            console.log(`this.current: ${this.current}`);
    }
}

I first encountered this error while working on a VS-Code extension (reported by VS-Code while editing the VS-Code extension). Apparently I can execute the code in 'playground' even though the error is reported, but VS-Code refuses to execute.

The fact that I can execute the code in 'playground' makes me wonder if the error is reported by typescript compiler or another tool.

Also note that replacing the condition:

        if (']' !== this.current)
            console.log(`this.current: ${this.current}`);

with:

    let ch = this.current;
    if (']' !== ch)
        console.log(`this.current: ${this.current}`);

eliminates the error.

What should I do to avoid this kind of error being reported ? Is it a typescript compiler bug ?

I am no typescript expert, so before reporting an issue to the typescript project I would like confirmation this is a real compiler bug.

enter image description here

0 Answers
Related