Real data is not always one type.
Direct answer
A union type, written with |, says a value can be one of several types. Before using a type-specific feature, narrow the type with a check like typeof. Literal unions limit values to specific strings or numbers.
Examples
let id: string | number;
id = "abc";
id = 123;
type Direction = "up" | "down" | "left" | "right";
function print(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
Discriminated unions
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(s: Shape) {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "square": return s.size ** 2;
}
}
Where Teyro fits
Teyro's TypeScript for Beginners course turns this into short lessons you can play in a few minutes a day. It has 20 lessons, and you can start free.
The bottom line
Unions describe real-world variety. Narrowing keeps you safe.


