I have this code:
function A(): never {
throw new Error("fail");
}
function B(): never {
A();
}
And I get this error:
index.ts(5,36): error TS2534: A function returning 'never' cannot have a reachable end point.
Why am I getting this error? Obviously, A
never returns and therefore B
does not have a reachable end point.
It is a limitation of the compiler. Ryan Cavanaugh explains here:
The limitation here has to do with the way the compiler is designed -- control flow analysis happens before typechecking, but we would need type information (as well as identifier resolution) to determine that the
fail()
call points to a function that is: never
The fail()
call in the context of this quote does essentially the same thing as A()
in the question asked here. I'm inferring from the quote above that by the time the control flow analysis is done, the fact that A()
cannot return is not known yet, so the assumption is that the implicit return undefined;
at the end of B
will be executed and thus B
will return undefined
rather than not return at all. The fix is as mentioned in the issue report from which the comment was taken, just add a return
before the call to a function that never returns:
function B(): never {
return A();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With