Quiz
Warm-up from lesson 2-3: you wrote let direction: "left" | "right". What does the | symbol mean in a type?
One variable, several possible types
A union type says a value is one of a fixed set of types:
type Id = string | number; function formatId(id: Id): string { return "ID-" + id; }
Database ids, user input, and web API fields are often "string or number" in real systems, and this is how you say so honestly. Note the type alias naming the union, which lesson 3-3 said interfaces cannot do.
The rule that makes unions safe: you may only do things that are valid for every member. String concatenation works for both members here, so "ID-" + id compiles. But id.toUpperCase() would be an error, numbers have no such method. To use member-specific operations you must first narrow, which is the next lesson.
Code exercise · typescript
Run it, both member types pass through the same function. Then add console.log(formatId(true)) and run again, boolean is not in the union.
Quiz
With function f(x: string | number), why does x.toUpperCase() fail to compile?