Sub topic 1
TypeScript Union Types: Modeling Alternatives and Combinations
Prerequisites
You should know basic TypeScript syntax, type aliases, primitive types, object types, and function parameter and return types.
A value that is one of several types
A union type uses | to say that a value may have one of several types. The code must handle every possible member before using member-specific operations.
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase();
}
return id.toFixed(0);
}
console.log(formatId("ab-12")); // AB-12
console.log(formatId(42)); // 42Before the typeof check, TypeScript cannot assume that id is a string or a number. After the check, it narrows the type inside each branch.
Literal unions for a fixed set of values
A literal union restricts a value to specific strings, numbers, or booleans. This models a fixed set of valid choices.
type Direction = "north" | "south" | "east" | "west";
function turnAround(direction: Direction): Direction {
switch (direction) {
case "north": return "south";
case "south": return "north";
case "east": return "west";
case "west": return "east";
}
}
console.log(turnAround("north")); // southA value such as "up" cannot be passed to turnAround, because it is not part of Direction.
What you can access on a union before narrowing
You can access only members that every union member has in common. For example, both a cat and a dog may have a name, but only a cat has meow.
type Cat = { name: string; meow(): void };
type Dog = { name: string; bark(): void };
function describe(pet: Cat | Dog): string {
if ("meow" in pet) {
pet.meow();
return `${pet.name} is a cat`;
}
pet.bark();
return `${pet.name} is a dog`;
}The in operator checks whether a property exists and narrows the union accordingly.
Narrowing with checks
TypeScript narrows unions using runtime evidence:
typeof value === "string"distinguishes primitive types."property" in valuedistinguishes object shapes.value === "specificValue"narrows literal unions.
Exercise
What is the type of value inside the if branch in if (value === "ready"), when value has type "ready" | "waiting"?
Show answer
It is narrowed to the literal type "ready".