Narrowing Unions
Common issue with unions
In this example, property 'toUpperCase' does not exist on type ‘number’
function printId(id: number | string) {
console.log(id.toUpperCase());
}
The solution is to narrow the union to deduce a more specific type for a value based on the structure of the code.
function printId(id: number | string) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}