-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Tagged type narrowing doesn't work when one of the tags is a union type #43026
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
I have a simpler use case of another instance where type narrowing doesn't work. The union type doesn't narrow unless the expression being checked in the let a : string | undefined;
if (new Date().getHours() > 4) {
a = "value";
}
let b = !!a;
if (b) {
a; // should be string, but is still union type
}
if (!!a) {
a; // type is narrowed to a string here.
} TypeScript Playground link: HERE |
@koushikkothagal That would be #12184 (when using |
The core problem is more easily explained in the expanded form if (value.type !== 'b') {
// ~~ here ~~
if (value.type !== 'c') { At this point, there's no type we can narrow |
If you add value.type in the if condition
Seems that in IDE Typescript is able to figure out the only |
I made a TS playground showing what is IMO an even more simple case. I also made a Flow try showing the exact same behavior, but with no errors type ABCDBroken =
| { status: 'A' | 'B'; extra: string }
| { status: 'C' | 'D' }
type ABCDWorking =
| { status: 'A' | 'B'; extra: string }
| { status: 'C' }
| { status: 'D' }
function testItOut(abcd: ABCDBroken) { // Replace `ABCDBroken` with `ABCDWorking` and see the problem magically resolve!
if (abcd.status === 'C' || abcd.status === 'D') {
return
}
let s: 'A' | 'B' = abcd.status // TS knows that `status` is narrowed to 'A' | 'B' ...
return abcd.extra // ... but it doesn't know that `extra` is available
} |
Bug Report
Tagged type narrowing doesn't work when one of the tags is a union type. Sorry, not sure how to be more descriptive
🔎 Search Terms
union narrowing
🕗 Version & Regression Information
3.9.7, 4.2.2, Nightly
This is a crashThis changed between versions ______ and _______I was unable to test this on prior versions because _______⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
Type of
a
is not narrowed toA
🙂 Expected behavior
Type of
a
is narrowed toA
The text was updated successfully, but these errors were encountered: