🧭Union Type
Also known as Union Types, Sum Type, Either Type
A type for a value that can be one of a few kinds. It may be text or a number.
Think of it like
It is like a box marked toys or books. You know it holds one of the two, and nothing else.
Example
An id field can hold 42 or "A-42". Lucy types it as number | string, and the checker makes her handle both.
Why it matters
Real data often comes in more than one shape. A union names every shape, so none is forgotten.
Definition
Example code
typescript
function show(id: number | string) {
if (typeof id === "number") return id.toFixed(0);
return id.toUpperCase();
}Common mistake
Key takeaways
- 1One of a few. The value is this type or that one.
- 2Check, then use. Each case is handled on its own.
- 3Missing values. Often written as a type or null.