Sub topic 1
Union types: a value that is one of several types
A union type describes a value that may belong to one of several types. TypeScript writes a union with the vertical bar (|). For example, string | number means “a string or a number.”
Prerequisites
This chapter assumes basic TypeScript syntax, type annotations, object types, type aliases, and function parameter and return types.
Declaring a union
A union is useful when one operation accepts different kinds of input. The following function accepts either a text identifier or a numeric identifier:
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase();
}
return id.toFixed(0);
}
console.log(formatId("user-42")); // USER-42
console.log(formatId(42)); // 42The parameter id has the type string | number. A caller can pass either member of the union, but the function must handle both possibilities.
Before TypeScript knows which type it has, only operations that are valid for every member are safe. For example, you cannot call id.toUpperCase() immediately because numbers do not have that method. You also cannot call id.toFixed() immediately because strings do not have that method.
Accessing common members
Suppose two object types form a union:
type Cat = {
name: string;
meow(): void;
};
type Dog = {
name: string;
bark(): void;
};
function getName(pet: Cat | Dog): string {
return pet.name;
}Both Cat and Dog have a name property, so pet.name is available without further checking. The meow and bark methods are not common to both types, so TypeScript rejects calls to either method until the union is narrowed.
A union does not merge all members into one large type. It exposes the intersection of the members that every possible value supports.
Narrowing a union
Narrowing is the process of using a runtime check to reduce a broad union to a more specific type. TypeScript understands several common checks:
typeof value === "string"narrows primitive unions."property" in valuechecks whether an object has a property.- Equality checks compare literal values.
- A shared discriminant property identifies an object variant.
For the Cat | Dog example, the in operator can identify the correct member:
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`;
}Inside the first branch, the presence of meow proves that pet is a Cat. After that branch, TypeScript knows that the remaining possibility is Dog.
Equality checks work well with literal unions. A literal type represents one exact value. For example, "north" is a string literal type, while string represents any string.
type Direction = "north" | "south" | "east" | "west";
function turnAround(direction: Direction): Direction {
if (direction === "north") {
return "south";
}
if (direction === "south") {
return "north";
}
if (direction === "east") {
return "west";
}
return "east";
}The Direction type prevents invalid values such as "up" from being passed to turnAround. The equality checks narrow direction to one literal at a time.
Visualizing narrowing
Common errors
A frequent error is assuming that a union gives access to every member from every option:
function bad(pet: Cat | Dog): void {
// pet.meow(); // Error: Dog may not have meow
// pet.bark(); // Error: Cat may not have bark
}Another error is widening a value accidentally. A variable declared as let direction = "north" may be inferred as string, because its value can later change. Use an explicit annotation when you need the fixed union:
let direction: Direction = "north";
direction = "west";
// direction = "up"; // ErrorUse unions when a value has several valid alternatives. Narrow the value before calling members that belong to only one alternative.
Exercise
Why does TypeScript allow pet.name in a function receiving Cat | Dog, but reject pet.meow without a check?
Show answer
Both Cat and Dog define name, but only Cat defines meow. The method is safe only after narrowing the union to Cat.