Sub topic 9
Unions and Literal Types: What Only Aliases Can Name
Prerequisites
Assume you know basic TypeScript annotations, JavaScript objects and functions, and how to run the TypeScript compiler. This chapter focuses on modeling a value that may have one of several forms.
A value with one of several types
A union type uses | to say that a value can match one type or another:
type Status = "idle" | "loading" | "done";
let status: Status = "idle";
status = "done";
// status = "failed"; // Error: not part of StatusThe strings in Status are literal types. A literal type represents one exact value, rather than every string. Literal types are useful when an API accepts a small, known set of choices.
A union can combine object types as well:
type Result =
| { ok: true; value: string }
| { ok: false; error: Error };This type describes two alternatives. A successful result has ok: true and value. A failed result has ok: false and error.
The shared ok property is a discriminant. TypeScript uses its value to narrow the union:
function describe(result: Result): string {
if (result.ok) {
return `Value: ${result.value}`;
}
return `Error: ${result.error.message}`;
}
console.log(describe({ ok: true, value: "saved" }));
console.log(describe({ ok: false, error: new Error("Network failure") }));After the if check, TypeScript knows which object shape is available. Accessing result.value in the failure branch would be an error.
Why type aliases are needed
An interface describes one object shape. It can extend another interface, but it cannot directly name a union such as "idle" | "loading" | "done" or combine alternative object shapes with |.
A type alias can name almost any TypeScript type, including unions, primitive types, tuples, function types, and intersections.
| Need | Suitable declaration |
|---|---|
| Several alternative shapes | Type alias |
| One named object contract | Interface or type alias |
You can still use interfaces for the individual members of a union:
interface Success {
ok: true;
value: string;
}
interface Failure {
ok: false;
error: Error;
}
type Result = Success | Failure;This separates reusable object contracts from the union that combines them.
Narrowing every alternative
For larger unions, a switch statement makes each case explicit. An exhaustive check catches missing cases when the union changes:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rectangle":
return shape.width * shape.height;
default: {
const impossible: never = shape;
return impossible;
}
}
}
console.log(area({ kind: "circle", radius: 2 }));never represents a value that cannot exist. If someone adds a new Shape variant without adding a case, the assignment to never produces a compile-time error.
The structural typing connection
Unions still use structural typing. A value matches a union when it matches at least one member's required structure. Extra properties may be accepted when the value comes from a variable, although fresh object literals receive stricter excess-property checks.
Exercise
Why is type Result = Success | Failure valid when interface Result extends Success, Failure is not an equivalent design?
Show answer
A union represents alternatives, so a value is either Success or Failure. Interface extension combines requirements, so an extending interface would need to contain every required member from both shapes.