While studying about equality narrowing in typescript, I came across a function example from the official handbook (view it on playground):
function example(x: string | number, y: string | boolean) {
if (x === y) {
// We can now call any 'string' method on 'x' or 'y'.
// As x and y can only be equal if they had type string
x.toUpperCase();
y.toLowerCase();
} else {
console.log(x); // x : string | number
console.log(y); // y : string | boolean
}
}
In the if
branch, both x
and y
are narrowed down to type string
. This allows us to use string methods. However, in the else
branch, both x
and y
still have string
as a possible type. Ideally, string
should not be present as a type in the else
branch. Is this a limitation of Typescript's current type system, or am I missing something crucial here? Your insights would be greatly appreciated. Thank you!