TypeScript Unions
A union type is a type that accepts a value of any one of several types. The members of the union are listed with a vertical bar between them.
One variable, two kinds
A string | number variable accepts a string and then a number. Each log shows the value stored at that step.
let id: string | number = "abc";
console.log(id);
id = 42;
console.log(id);A member-only method is refused
The toUpperCase method belongs to string and not to number. The call fails on the union as a whole.
function shout(value: string | number) {
console.log(value.toUpperCase());
}
shout("hello");A typeof check handles each member
The typeof check splits the union inside the function. Strings take one branch, and numbers take the other.
function show(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value + 1);
}
}
show("hello");
show(41);Example
function printId(id: string | number) {
if (typeof id === "number") {
console.log("ID-" + id);
} else {
console.log(id);
}
}
printId(7);
printId("user-9");Key points
- A union accepts a value of any one of its member types.
- The compiler allows only operations that work for every member.
- A typeof check narrows a union to one member inside a branch.
- A union can list more than two member types.
In this example, printId takes a string | number union. The number call takes the first branch and gains the ID- prefix. The string call takes the second branch and prints as stored.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does the type string | number accept?