-
Notifications
You must be signed in to change notification settings - Fork 12.8k
No implicit returns error in exhaustive if statement #17358
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
Is not exhaustive you can call fn function as So, I think, that works as intended. |
@j-oliveras I think what you're saying makes sense, but I don't see how that applies to this example: interface A { type: 'A' }
interface B { type: 'B' }
// error: Not all code paths return a value.
const fn = (x: A | B) => {
if (x.type === 'A') {
x // A
return 1
} else if (x.type === 'B') {
x // B
return 2
} else {
x // never
}
} If using a |
@j-oliveras It is exhaustive as far as the type checker is concerned, since it infers a The simplest repro I can imagine is something like: function foo(x: boolean) {
if (x) return 1;
if (!x) return 2;
// x is inferred as never here, but ts still thinks some paths don't return a value
} I'm guessing that the real issue is that the control flow analysis just isn't clever enough to realize that, once it has narrowed something to the |
I believe the problem is that only You can always return the result of calling |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
This also affects switch statements when they exist within an Is there anything TS can do to help here? {
enum Input { foo, bar }
// Unexpected error: Not all code paths return a value.
const fn = (input: Input) => {
if ('foo') {
switch (input) {
case Input.bar: return 0;
case Input.foo: return 1;
}
} else {
return 1
}
}
// Workaround: wrap switch in IIFE
const fn2 = (input: Input) => {
if ('foo') {
return (() => {
switch (input) {
case Input.bar: return 0;
case Input.foo: return 1;
}
})();
} else {
return 1
}
}
} |
|
@jcalz Thanks, that works. TypeScript already special cases |
I have the same problem with nested switch clauses : |
TS 2.4.1 with
noImplicitReturns
enabledI would not expect this to error because the if statement is exhaustive, therefore all code paths do return a value.
The text was updated successfully, but these errors were encountered: