-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Surprising Not all code paths return a value
#18319
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
Comments
Doesn't require async type fn = () => (void | number);
var x: fn = () => {
if (Math.random()) {
return 1;
}
} I'm not really sure if this error is "unexpected" or not. It's controlled by the "No implicit returns" flag and this is definitely an implicit return. |
Just wanted to point out that this generally works without errors with the "No implicit returns" flag: class Foo {
maybeReturn(): string | void {
if (Math.random() > 0.5) {
return 'hello';
}
}
} |
PRs welcome |
Related bug in v3.7.2. // Error TS2366: Function lacks ending return statement and return
// type does not include 'undefined'.
function f(x: number): number {
if (typeof x === 'number') {
return 1
}
} Notably, this prevents you from expressing React props as unions: import * as React from 'react'
type Props =
| { a: number }
| { b: string }
// Error TS2366: Function lacks ending return statement and return
// type does not include 'undefined'.
function MyComponent(props: Props): JSX.Element {
if ('a' in props) {
return <div>a is {props.a}</div>
}
if ('b' in props) {
return <div>b is {props.b}</div>
}
} For this example to type check, we need to add a catch-all |
Not sure if related to this but I get the same behavior when returning const aa = (a: any) => { // No error
if (a) return
}
const bb = (b: any) => { // Not all code paths return a value.
if (b) return void console.log("foo")
}
|
@mhegazy since some time has gone by: is this still "PRs welcome"? |
compilerOptions:{ |
How is a |
TypeScript Version: 2.5.2
Code
Expected behavior:
No tsc errors.
Actual behavior:
Notably, when using return-type annotation, this error does not occur:
In our real-world scenario, it would not be sufficient to look for this syntactic pattern. Rather, the fact that the async function is assigned to a union containing void should be the trigger that silences this error.
The text was updated successfully, but these errors were encountered: