Description
Bug Report
π Search Terms
discriminated union narrowing
π Version & Regression Information
4.6.2
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about discriminated unions and narrowing
β― Playground Link
Playground link with relevant code
π» Code
The linked example above shows how to reproduce. The broken
function in the example has x
on line 35 inferred as { readonly type: "foo"; }
. It should be narrowed in this position to never
.
This behavior prevents the following common pattern from being used when you only have 1 member of a discriminated union (which is realistic if you are building the "first type" and plan to build others later):
// utility for catching non-exhaustive switches
class UnexpectedCase extends Error {
constructor(value: never) {
super(`Did not expect to reach case: ${JSON.stringify(value)}`);
}
}
interface FirstType { type: 'FirstType' }
type Types = FirstType; // later we will add 'SecondType' and so on
function transform(x: Types) {
switch (x.type) {
case 'FirstType':
return // create something else
default:
// we want to get a type error here in the future when we have missing cases, but we are already getting
// one now because the type system isn't narrowing `x` to `never`
throw new UnexpectedCase(x); // TS error: argument of type 'FirstType' is not assignable to never
}
}
Yes I'm aware that this technically isn't a discriminated union, but it shouldn't make a difference. The point is that the type system isn't narrowing the type of a variable to never
when it clearly (in a statically knowable way) cannot have a value in this branch.
π Actual behavior
The type system is not narrowing x
to never
in the example above in the default
case, even though this case cannot be reached.
π Expected behavior
x
should be narrowed to never
in the default
case because that code cannot be reached. This is the only sensible behavior if we want to say never
is a bottom type.