-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
empty return statement should be a compiler error when return type is specified #5916
Comments
function foo(x: number | string | boolean): string {
if(typeof x === 'number') {
return x.toString();
} else if (typeof x === 'string') {
return x;
}
} as a note, currently if you compile this code snippet using current bits from master branch with
|
Ah -- that's exactly what I was looking for. Thanks @vladima! I'm guessing this will be in |
yes. And it is already in |
so does this take care of the issue in OP? |
I don't entirely think so; this does't cover accidentally omitting a return expression. But I shouldn't put words in @tejacques' mouth, so I'll let him speak for himself. 😄 |
we can make |
@DanielRosenwasser is right -- this is really close now, but I would like to see an expression required. I personally don't think it's too restrictive because the programmer has already declared their intent by specifying a return type on the function. If it remains as a flag, then doubly-so because it is opt-in. It's also a lot clearer that it is intentionally returning |
@vladima thoughts? |
Accepting PRs. Make this an error only under the |
Just for the interest of people here. Note the original example: function foo(x): string {
return;
} will automatically be an error in |
thanks @martine! |
Should this not be allowed?
|
Currently this function compiles just fine
I understand that it's happening because
undefined
is a valid result for a variable of typestring
, and this sort of related back to #185, but a midway point could be to simply require the return statement to not be empty.Similarly, this code fails to compile:
But this one compiles:
I think the expected behavior is that every branch should require an explicit return statement.
A side benefit of this is that you can get exhausting matching completeness basically for free:
Currently the above compiles, but if TypeScript required an explicit return in every branch for non void return functions, there would be a compiler error because there are remaining types in the union. However this would compile:
This is pretty nice! There is one edge case still -- because of the implicit
void
included inx
, callingfoo(null)
orfoo(undefined)
will returnundefined
. I don't know what to do about this because it relates pretty heavily to #185. I think for now it can be ignored, and whatever resolution that (hopefully) happens there will take care of it.The text was updated successfully, but these errors were encountered: