Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get TypeScript to figure that my function cannot possibly return?

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.

like image 587
Louis Avatar asked Dec 06 '16 19:12

Louis


1 Answers

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();
}
like image 133
Louis Avatar answered Oct 18 '22 02:10

Louis