-
Notifications
You must be signed in to change notification settings - Fork 12.8k
control flow analysis incorrectly narrows type to never
when type-guarded
#45664
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is the correct behaviour. Your variable You see the behaviour you expect if you type You have the same behaviour in TypeScript 4.3.5 when you replace |
That
|
To clarify, it sees this not because of the |
I don't think TypeScript sees You can validate this by checking that |
Looks like I have the wrong minimal testcase. This is what I intended to do, let me know if I should open a different issue: interface Box {
isSmallBox(): this is SmallBox;
isLargeBox(): this is LargeBox;
sayHello(): any;
}
interface SmallBox extends Box {
sayTruth(): boolean;
}
interface LargeBox extends Box {
}
function hello(a: SmallBox|LargeBox, b: SmallBox|LargeBox) {
const isLargeBox = a.isLargeBox() || b.isLargeBox();
if(isLargeBox) {
a.sayHello();
} else {
a.sayHello();
}
}
function hello(a: Box, b: Box) {
const isLargeBox = a.isLargeBox() || b.isLargeBox();
if(isLargeBox) {
a.sayHello();
} else {
a.sayHello();
}
} In both functions, the second |
Ignore that. The issue is that @pomack Everything that This is why I personally prefer to be explicit using discriminated unions:
Here you have a dedicated property to explicitly distinguish the different types. |
Thanks @MartinJohns Will add the explicit attribute. |
Bug Report
The new control flow analysis incorrectly narrows a type that is type-guarded to fallback to
never
in the else clause when they should either remove the type-guarded type or stay the original type if not explicitly typed earlier. They should only fallback tonever
when all types are exhausted (if enum or was an initial set of types).🔎 Search Terms
control flow analysis
never
type narrowing
type guard
🕗 Version & Regression Information
⏯ Playground Link
Playground link for 4.3.5 (no error)
Playground link for 4.4.2 (error)
Playground link for 4.5.0-dev.20210831 (error)
💻 Code
🙁 Actual behavior
The last
b.sayHello()
hasb
as typenever
, causing an error.🙂 Expected behavior
The last
b.sayHello()
should haveb
as typeSmallBox
The text was updated successfully, but these errors were encountered: