You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A function that never returns (return type never) can not be used in a type guard to narrow the type after the branch.
Code
classThing{};functiondiverges(): never{thrownewError('Never returns');}functionproblem(thing: Thing|null): Thing{if(thing===null){diverges();// throw new Error('Works!');}returnthing;// fails type check}
Expected behavior:
Replacing the call to diverges() with a return or throw statement causes thing to be marked as type Thing after the branch, as code will never flow from the if (thing === null) branch to the code below. I expected a call to a function with return type never to achieve the same, as this should indicate that the call never returns.
Actual behavior:
The code does not compile due to an error, as the type of thing is not narrowed to Thing:
"Type 'Thing | null' is not assignable to type 'Thing'. Type 'null' is not assignable to type 'Thing'."
The text was updated successfully, but these errors were encountered:
I suspect this won't happen, because it is possible to return a never-type value, which means it's possible for that function to complete and return and control to move on down to return thing;.
TypeScript Version: 2.3.2
A function that never returns (return type
never
) can not be used in a type guard to narrow the type after the branch.Code
Expected behavior:
Replacing the call to
diverges()
with a return or throw statement causes thing to be marked as typeThing
after the branch, as code will never flow from theif (thing === null)
branch to the code below. I expected a call to a function with return typenever
to achieve the same, as this should indicate that the call never returns.Actual behavior:
The code does not compile due to an error, as the type of
thing
is not narrowed toThing
:"Type 'Thing | null' is not assignable to type 'Thing'. Type 'null' is not assignable to type 'Thing'."
The text was updated successfully, but these errors were encountered: