Closed as not planned
Description
🔎 Search Terms
"type guard typescript not working for single case switch"
🕗 Version & Regression Information
This changed between versions ______ and _______This changed in commit or PR _______This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________I was unable to test this on prior versions because _______- I tested this in typescript playground for versions 5.6.2, 4.6.4, and 3.3.3
⏯ Playground Link
💻 Code
type Foo = {
type: 'a',
a: string,
}
function foo(foo: Foo) {
switch (foo.type) {
case 'a':
console.log(foo.a)
return;
default:
const _exhaustiveCheck: never = foo;
}
}
type Bar = {
type: 'a',
subtype: 'a',
a: string,
} | {
type: 'a',
subtype: 'b',
b: string,
}
function bar(bar: Bar) {
switch (bar.type) {
case 'a':
console.log('a' in bar ? bar.a : bar.b)
return;
default:
const _exhaustiveCheck: never = bar;
}
}
🙁 Actual behavior
No type reduction occurs in the default case. Typescript marks foo
not assignable to type never
.
🙂 Expected behavior
Both foo
and bar
should be reduced to type never
in the default case.
Additional information about the issue
Related: #2214
Workaround:
Manually exclude types from foo
that are handled by case 'a'
.
type Foo = {
type: 'a',
a: string,
}
function foo(foo: Foo) {
switch (foo.type) {
case 'a':
console.log(foo.a)
return;
default:
const _exhaustiveCheck: never = foo as Exclude<typeof foo, { type: 'a' }>;
}
}