-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
'return' statement required after function that returns 'never' #10470
Comments
Somewhat related: #8655 |
A simple fix is: function foo(bar: number): string | undefined {
if (bar = 0) return 'off';
if (bar > 1) return 'on';
assert(false, 'Invalid value for bar');
} It does appear to essentially be a dupe of #8655 in the sense that this is valid: function foo(bar: number): string {
// Unimportant
if (bar = 0) return 'off';
if (bar > 1) return 'on';
throw new Error('Invalid value for bar');
} On the other hand, |
@kitsonk
the problem would be the same. The suggested solution adds To satisfy the compiler, I think I'm better of with adding just a return statement:
|
I totally understand what the // Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is number
function move1(direction: "up" | "down") {
switch (direction) {
case "up":
return 1;
case "down":
return -1;
}
return error("Should never get here");
}
// Inferred return type is number
function move2(direction: "up" | "down") {
return direction === "up" ? 1 :
direction === "down" ? -1 :
error("Should never get here");
}
// Inferred return type is T
function check<T>(x: T | undefined) {
return x || error("Undefined value");
} And to quote:
|
The 'problem' I have is when there is code after a function that never returns. The compiler warns that there is a code path that doesn't return a value. |
The intended fix is return assert(false, 'Invalid value for bar'); There are technical reasons why we can't figure this out correctly today but I'm not remembering exactly why right now. I'll follow up. |
Thanx |
How can I resolve these errors here? [ts] Function lacks ending return statement and return type does not include 'undefined'. |
By asking "how to use TypeScript" questions on StackOverflow or Gitter? |
@kitsonk 💯 |
TypeScript Version: 2.1.0-dev.20160819
Code
Expected behavior:
I would expect if the type system knows that
assert(false, '')
never returns, it doesn't require a return statement afterassert
.Actual behavior:
Error on foo function:
Function lacks ending return statement and return type does not include 'undefined'
The text was updated successfully, but these errors were encountered: