TypeScript Union Types
A union type allows a variable to hold one of several specified types, written by separating the types with a vertical bar `|`. This is useful when a value can legitimately be more than one type.
When working with a union, TypeScript only allows you to use operations that are valid for every type in the union, unless you first narrow the type down to one specific option.
let id: string | number;
id = 101;
id = "A101";Declaring a union
You write a union type as `string | number`, meaning the value can be either a string or a number. Function parameters commonly use unions to accept flexible input.
Using union values safely
Before calling type-specific methods, you typically check the type with `typeof` or another narrowing technique so TypeScript knows exactly which type you're working with.
function printId(id: string | number) {
console.log(`ID: ${id}`);
}
printId(101);
printId("A101");ID: 101
ID: A101The function accepts either a string or a number thanks to the union type.
function formatId(id: string | number): string {
if (typeof id === "number") {
return id.toFixed(0);
}
return id.toUpperCase();
}
console.log(formatId(5));
console.log(formatId("abc"));5
ABCA typeof check narrows the union so the correct type-specific method can be called safely.
Key points
- Union types are written with a vertical bar, like string | number.
- A union value can hold any one of the listed types.
- You must narrow a union before using type-specific methods.
- Unions make functions more flexible while staying type-safe.
