Inside the test
function, b
type does not narrow to string
when a
type is string
.
Why? I don’t understand why it behaves this way.
type Foo = {
a: string;
b: string;
};
type Bar = {
a: number;
b: number;
};
type Uinon = Foo | Bar;
function test({ a, b }: Uinon) {
if (typeof a === "string") {
a;
b;
}
}
playground
If a is type literal as shown below, this is fine, but if it is not type literal, why is it not type narrowing?
type Foo = {
a: "A";
b: string;
};
type Bar = {
a: "B";
b: number;
};
Jaedeok Kim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The feature you are using is not type narrowing, but rather a discriminated union. From (apparently outdated) documentation:
Discriminating Unions
A common technique for working with unions is to have a single field which uses literal types which you can use to let TypeScript narrow down the possible current type. For example, we’re going to create a union of three types which have a single shared field.
And this discrimination is only implemented for literal types.