TypeScript · Beginner · 10 min
Unions and narrowing
Handle each allowed kind of value before using its specific operations.
Allow more than one type
A union means a value may have any one of the listed types. Before using an operation that belongs to only one member, narrow the value with a runtime check.
function show(id: string | number): string {
return typeof id === "string" ? id.toUpperCase() : id.toFixed(0);
}
console.log(show("ab"));Output
AB
Check before using
TypeScript follows control flow after a typeof check. This makes operations available in the branch where they are valid. The check also runs in JavaScript.
function double(value: string | number): number {
if (typeof value === "string") return Number(value) * 2;
return value * 2;
}
console.log(double("4"));Output
8
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Narrow before uppercasing
Make "format" uppercase a string and convert a number with String(). Display the result for 7.
Check typeof before calling toUpperCase().
Put it into practice
- Read the types and predict the output before running the examples.
- Complete the task, then check your understanding with the practice questions.