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

In the following Typescript code, the compiler says that the doit property does not exist in the type 'never'. Could this be a compiler error?

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 has no problems with this equivalent code, which again makes me suspect that there is a compiler error.

+5
source share
1 answer

Yes, it seems to be a mistake: InstanceOf is narrowed incorrectly when two types extend the same base class .

But no matter what is the point of what you are doing?
If you want foo to behave differently in cases of Y , then why not redefine it in Y :

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

And if doit is only required in instances of Y , it should be in Y , if necessary, both can be protected in X

+1
source

Source: https://habr.com/ru/post/1260317/


All Articles