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
{{ message }}
Repository navigation
Call to function returning never can not be used to narrow type #15991
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'."
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;.
Activity
krryan commentedon May 22, 2017
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 toreturn thing;.RyanCavanaugh commentedon May 22, 2017
Duplicate #12825. The recommended workaround is to write
return diverges();RyanCavanaugh commentedon May 22, 2017
The intent of
neveris that it shouldn't be possible.bwrrp commentedon May 23, 2017
Sorry, must have missed that one in my search. Thanks for the explanation!