Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'x' does not exist on type 'never'

Tags:

typescript

In the following code Typescript compiler says property 'doit' does not exist on type 'never'. Could this be a compiler bug?

class X {
    public foo(): void {
        if (this instanceof Y) {
        } else {
            this.doit();
        }
    }

    private doit(): void {
    }
}

class Y extends X {
}

I found the following workaround:

const temp = (this instanceof Y);
if (temp) {
} else {
    this.doit();
}

The compiler does not have any issues with this equivalent code, which again leads me to suspect there is a compiler bug here.

like image 214
User52016 Avatar asked Nov 09 '22 05:11

User52016


1 Answers

Yeah, it seems to be a bug: InstanceOf incorrectly narrow when two type extends same base class.

But, regardless, what is the point of what you're doing?
If you want foo to behave differently in instances of Y then why not override it in Y:

class Y extends X {
    public foo(): void {
        ...
    }
}

And if doit is only needed in Y instances it should be in Y, if it's needed in both it can be protected in X.

like image 153
Nitzan Tomer Avatar answered Nov 15 '22 12:11

Nitzan Tomer