Sub topic 9
Unions and literal types: what only aliases can name
This chapter assumes you know basic type annotations, how to declare an interface or a simple type alias, and how structural typing works. It covers the one job that only a type alias can do: giving a name to a union.
Literal types
A literal type is a type that holds exactly one value. The type "idle" accepts the string "idle" and nothing else. The same applies to numbers (404) and booleans (true).
A union type joins several types with |. A value of a union type must match at least one member. Combining literals and unions gives you a small, closed set of allowed values.
type Status = "idle" | "loading" | "done";
let current: Status = "idle";
current = "loading"; // allowed
// current = "finished"; // error: Type '"finished"' is not assignable to type 'Status'.This is usually better than a plain string. The compiler rejects typos, and your editor can suggest the valid values.
Why only aliases can name a union
An interface always describes an object shape. A union is not a single object shape. It is a choice between several types, and some of those types may not be objects at all ("idle" is a string). The syntax interface Status = ... does not exist, so you need a type alias.
The same limit applies to other non-object types. You can alias a primitive, a tuple, or a union of anything:
type Id = string | number;
type Coordinates = [number, number];
type MaybeName = string | null | undefined;An interface can still be a member of a union. The union itself needs the alias:
interface Cat {
meow(): void;
}
interface Dog {
bark(): void;
}
type Pet = Cat | Dog;Unions of object types
Unions become more useful when each member is an object type. A union of objects that share a property with a literal type is called a discriminated union. The shared property is the discriminant.
type Result =
| { ok: true; value: string }
| { ok: false; error: Error };
function describe(r: Result): string {
return r.ok ? r.value : r.error.message;
}Narrowing is how TypeScript refines a union to a smaller type based on a check. In describe, the test r.ok tells the compiler which member it is looking at. In the true branch r is { ok: true; value: string }, so r.value is valid. In the false branch r is { ok: false; error: Error }, so r.error is valid.
Without the check, the compiler allows only what every member shares:
function broken(r: Result): string {
// return r.value; // error: Property 'value' does not exist on type '{ ok: false; error: Error }'.
return String(r.ok); // fine: 'ok' exists on every member
}Narrowing with a switch
A switch on the discriminant is the common way to handle each case. Add an exhaustiveness check so the compiler tells you when a new member is not handled.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
case "rectangle":
return shape.width * shape.height;
default: {
const unreachable: never = shape;
return unreachable;
}
}
}
console.log(area({ kind: "square", side: 3 })); // 9The type never has no values. If every case is handled, shape in the default branch has type never, and the assignment compiles. If you add { kind: "triangle"; ... } to Shape and forget a case, shape becomes the triangle type, the assignment fails, and the compiler points to the function that needs updating.
Unions without a discriminant
A union does not need a discriminant property. Other checks also narrow it:
| Check | Narrows by | Example | Column |
|---|---|---|---|
| `typeof x === "string"` | primitive type | `string \ | number` |
| `x instanceof Date` | class | `Date \ | string` |
| `"bark" in x` | property presence | `Cat \ | Dog` |
| `x === null` | equality | `string \ | null` |
| `Array.isArray(x)` | array check | `string \ | string[]` |
Here is the in check applied to the Pet union:
interface Cat {
meow(): void;
}
interface Dog {
bark(): void;
}
type Pet = Cat | Dog;
function speak(pet: Pet): void {
if ("meow" in pet) {
pet.meow();
} else {
pet.bark();
}
}A discriminant property is usually easier to maintain than an in check, because it states the intent directly and does not depend on which properties happen to be present.
Unions and structural typing
Unions follow the same structural rules as everything else. A value is assignable to a union if it is assignable to at least one member. That has a consequence for object literals with extra properties:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
const ok: Shape = { kind: "circle", radius: 2 };
// const bad: Shape = { kind: "circle", side: 2 };
// error: the literal must match one member; 'side' is not valid for the circle member.The discriminant lets the compiler pick the intended member and report errors against it, which gives clearer messages than a union with no shared literal property.
Literal widening
A literal type can silently widen to its base type. A const declaration keeps the literal type. A let declaration, or a property in an object literal, widens it to string:
type Direction = "up" | "down";
const a = "up"; // type "up"
let b = "up"; // type string
const config = { dir: "up" }; // config.dir is string
function move(d: Direction): void {
console.log(d);
}
move(a); // fine
// move(b); // error: Argument of type 'string' is not assignable to parameter of type 'Direction'.
// move(config.dir); // same errorThere are two common fixes. You can annotate the variable, or use as const to keep the literal types and mark the properties readonly:
const config2 = { dir: "up" } as const; // { readonly dir: "up" }
move(config2.dir); // fine
const config3: { dir: Direction } = { dir: "up" }; // fine
move(config3.dir);Deriving a union from a list of values
If you already have an array of allowed values, you can derive the union from it instead of writing it twice. as const makes the array a readonly tuple of literals, and typeof plus an indexed access turns it into a union.
const levels = ["debug", "info", "warn", "error"] as const;
type Level = (typeof levels)[number]; // "debug" | "info" | "warn" | "error"
function isLevel(value: string): value is Level {
return (levels as readonly string[]).includes(value);
}
console.log(isLevel("info")); // true
console.log(isLevel("verbose")); // falseThe function isLevel is a type guard. Its return type value is Level tells the compiler that, when the function returns true, the argument has type Level. Use this pattern to validate untrusted input such as query parameters or JSON.
Template literal types
A literal type can also be built from other literal types. A template literal type uses the same backtick syntax as a template string:
type Axis = "x" | "y";
type Side = "top" | "bottom";
type Edge = `${Side}-${Axis}`; // "top-x" | "top-y" | "bottom-x" | "bottom-y"When a template contains a union, TypeScript produces every combination. Keep an eye on the size: two unions of ten members each produce a hundred members.
Unions and interfaces together
Interfaces and unions work well together. A common pattern is to define each variant as an interface and combine them with an alias:
interface LoadingState {
status: "loading";
}
interface SuccessState {
status: "success";
data: string[];
}
interface ErrorState {
status: "error";
message: string;
}
type RequestState = LoadingState | SuccessState | ErrorState;
function render(state: RequestState): string {
switch (state.status) {
case "loading":
return "Loading...";
case "success":
return state.data.join(", ");
case "error":
return `Failed: ${state.message}`;
}
}Each variant stays individually reusable, and you can still extend or implement it. The alias provides the union. Because the switch covers every case, TypeScript knows render always returns a string, so no default branch is needed under strict.
Common mistakes
- Accessing a member that only some variants have. Narrow first. The compiler allows only the properties shared by every member.
- Using
stringwhere a literal union would do. A plainstringaccepts typos. Use a union for a closed set of values. - Forgetting that
letand object properties widen. Useas constor an explicit annotation. - Using an optional property instead of a union.
{ value?: string; error?: Error }allows states such as both being set or both missing. A discriminated union rules those out. - Skipping the exhaustiveness check. Without the
neverassignment, a new variant will compile and fall through silently. - Expecting runtime types. Unions and literals exist only at compile time. The
isLevelguard is needed because the compiler cannot check a value that arrives at runtime.
Summary
- A literal type holds one value, and a union lets a value be one of several types.
- Only a type alias can name a union, because an interface describes a single object shape.
- A shared literal property turns a union of objects into a discriminated union that narrows with
iforswitch. - Assign to
neverin thedefaultbranch to make the compiler flag unhandled cases. - Use
as constor annotations to stop literals from widening tostring.
Exercise
Define a discriminated union named Payment with two members: a card payment (method: "card", last4: string) and a bank transfer (method: "transfer", iban: string). Then write label(p: Payment): string that returns Card ending in 1234 style text for cards and Transfer from <iban> for transfers, with an exhaustiveness check.
Show answer
type Payment =
| { method: "card"; last4: string }
| { method: "transfer"; iban: string };
function label(p: Payment): string {
switch (p.method) {
case "card":
return Card ending in ${p.last4};
case "transfer":
return Transfer from ${p.iban};
default: {
const unreachable: never = p;
return unreachable;
}
}
}
Exercise
Why does interface Id = string | number; not compile, and what is the correct declaration? Can an interface be a member of a union?
Show answer
An interface declares an object shape and has no syntax for naming a union or a primitive. Use a type alias instead: type Id = string | number;. An interface can be a member of a union, such as type Pet = Cat | Dog;, but the union itself must be named with an alias.
Exercise
The code below fails to compile. Explain why and give two fixes. type Direction = "up" | "down"; function move(d: Direction): void {} const config = { dir: "up" }; move(config.dir);
Show answer
Properties of an object literal widen to their base type, so config.dir has type string, which is not assignable to Direction. Fix 1: use as const, as in const config = { dir: "up" } as const;. Fix 2: annotate the variable, as in const config: { dir: Direction } = { dir: "up" };.