Sub topic 1
Union types: a value that is one of several types
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic TypeScript syntax and type annotations.
- Use primitive types, object types, and type aliases.
- Declare function parameter and return types.
- Run code with
strictmode on. Every example assumesstrict: trueintsconfig.json, which includesstrictNullChecks.
What a union type is
A union type describes a value that is one of several listed types. You write it with the | operator between the member types:
let id: string | number;
id = "abc-123"; // ok: a string is one of the members
id = 42; // ok: a number is also a member
// @ts-expect-error boolean is not a member of string | number
id = true;The @ts-expect-error comment tells the compiler that the next line must contain an error. If the error disappears, the compiler reports the comment itself as unused. This chapter uses it to show code that is rejected while keeping the examples compilable.
You can use a union anywhere a type is allowed: parameters, return types, variables, properties, and generic arguments.
type Id = string | number;
function printId(id: Id): void {
console.log(`ID: ${id}`);
}
function parseId(raw: string): Id {
const asNumber = Number(raw);
return Number.isNaN(asNumber) ? raw : asNumber;
}
printId(101);
printId(parseId("A-101"));The return type of parseId tells every caller that the result might be either kind. The compiler then forces callers to deal with that.
The working model: a union is a set of values
A useful way to think about a type is as the set of values it accepts. string is the set of all strings. number is the set of all numbers. string | number is the union of those sets: every value that is in either one.
Two assignability rules follow from this model.
- A value of any member type can be assigned to the union. A
stringis already insidestring | number. - A union value can be assigned to a target only if every member of the union is assignable to that target. The value could be any member, so all of them must fit.
type Id = string | number;
function takesString(s: string): void {
console.log(s.length);
}
function demo(id: Id, s: string): void {
const widened: Id = s; // rule 1: a member goes into the union
console.log(widened);
// @ts-expect-error rule 2: number is not assignable to string
takesString(id);
}The same rules apply between unions. A narrower union can go into a wider one, but not the other way around:
type Small = string | number;
type Large = string | number | boolean;
function widen(value: Small): Large {
return value; // every member of Small is also in Large
}
function narrow(value: Large): Small {
// @ts-expect-error boolean is not in Small
return value;
}What the compiler lets you do with a union
Because the value could be any member, the compiler allows only operations that are valid for every member. This is the most common source of confusion for people new to unions.
function lengthOf(x: string | string[]): number {
return x.length; // ok: both string and string[] have length
}
function describe(x: string | number): string {
return x.toString(); // ok: both have toString
}
function shout(x: string | number): string {
// @ts-expect-error toUpperCase does not exist on number
return x.toUpperCase();
}The error is useful. If x is a number at runtime, x.toUpperCase() would throw a TypeError. The compiler stops you from writing that call without first checking which member you hold. Checking is called narrowing, and a later chapter covers it in depth. As a preview, a typeof check inside an if narrows the type for the code in that branch:
function shoutSafely(x: string | number): string {
if (typeof x === "string") {
return x.toUpperCase(); // x is string here
}
return x.toFixed(0); // x is number here
}Unions of object types
Property access works the same way with objects. Only properties that exist on every member are available.
type Circle = { radius: number };
type Rect = { width: number; height: number };
type Shape = Circle | Rect;
function tryRadius(shape: Shape): number {
// @ts-expect-error radius does not exist on Rect
return shape.radius;
}An object value also does not have to be exactly one member. This compiles:
type Circle = { radius: number };
type Rect = { width: number; height: number };
type Shape = Circle | Rect;
const both: Shape = { radius: 1, width: 2, height: 3 };
console.log(both);For a plain object union like this, the compiler checks excess properties against the properties of all members together. The object above has everything Circle needs, so it is a valid Circle, and the extra properties are not flagged. The union means "at least one member", not "exactly one member". If you need exactly one, you add a shared tag property that tells the members apart. That design is covered in the chapter on discriminated unions.
Unions and null
With strictNullChecks on, null and undefined are not part of other types. You add them with a union:
function greet(name: string | null): string {
if (name === null) {
return "Hello, guest";
}
return `Hello, ${name.toUpperCase()}`;
}
console.log(greet(null));
console.log(greet("ada"));The optional marker ? is shorthand for a union with undefined. A parameter x?: string has type string | undefined inside the function. A property { nickname?: string } accepts string | undefined. With exactOptionalPropertyTypes enabled, optional properties are stricter and undefined must be written out explicitly.
Precedence: where the parentheses go
The | operator binds more loosely than the array suffix []. It also binds more loosely than the arrow in function types, in the sense that a union written in a return position belongs to the return type. These rules cause real mistakes.
type A = string | number[]; // a string, or an array of numbers
type B = (string | number)[]; // an array whose items are strings or numbers
type C = () => string | number; // a function returning string | number
type D = (() => string) | number; // a function, or a number
const a: A = "text";
const b: B = [1, "two", 3];
const c: C = () => 1;
const d: D = 5;
console.log(a, b, c(), d);When a union appears inside another type constructor, add parentheses even where they might be optional. Readers then do not need to remember the precedence rules.
For long unions, you can put a leading | on each line. It is legal and makes diffs cleaner:
type Status =
| "idle"
| "loading"
| "done"
| "failed";Union of arrays or array of unions
These two types look similar and behave differently.
function addOne(list: string[] | number[], mixed: (string | number)[]): void {
mixed.push(1); // ok: any string or number may be added
mixed.push("two"); // ok
// @ts-expect-error list is one specific array type, but we do not know which
list.push(1);
}A (string | number)[] is one kind of array that holds mixed items. A string[] | number[] is one of two kinds of array. The compiler cannot tell which one list is, and a number may not be pushed into a string[]. The only argument that would be safe for both signatures is one that is both a string and a number, and no such value exists. The compiler therefore reports the parameter type as never.
Array literals follow the same idea when the compiler infers a type. [1, "two", 3] is inferred as (string | number)[], a union of the element types.
const items = [1, "two", 3]; // (string | number)[]
const first = items[0]; // string | number
console.log(first);How unions simplify
The compiler normalizes unions as it builds them. You will see the results in hover text and error messages, so it helps to recognize them.
| You write | The compiler treats it as | Why | Column |
|---|---|---|---|
| `string \ | string` | `string` | Duplicate members are removed |
| `string \ | "a"` | `string` | The literal `"a"` is already inside `string` |
| `string \ | never` | `string` | `never` is the empty set and adds nothing |
| `string \ | unknown` | `unknown` | `unknown` already contains every value |
| `string \ | any` | `any` | `any` absorbs everything |
| `boolean` | `true \ | false` | `boolean` is itself a union of two literals |
The second row has a practical consequence. If you write type Color = string | "red" | "green", the editor will not suggest "red" or "green", and any string is accepted. Literal unions are covered in the next chapter, and they work only when no wider type swallows the literals.
Note that the boolean row means boolean is already a union. The union rules therefore apply to it, and narrowing by true or false works like narrowing any other union.
Common mistakes
| Mistake | What happens | Fix | Column | Column |
|---|---|---|---|---|
| Calling a member-specific method on the union | Error: property does not exist on one of the members | Narrow first, for example with `typeof` | ||
| Assuming a union value is assignable to one of its members | Error: the other members do not fit | Narrow, or widen the target type | ||
| Writing `string \ | number[]` when you meant an array of both | Wrong type, often with confusing errors later | Write `(string \ | number)[]` |
| Using `string[] \ | number[]` and then calling `push` | Argument error mentioning `never` | Use `(string \ | number)[]` if the array is mixed |
| Believing the union means "exactly one member" | Objects with properties from several members are accepted | Add a tag property, as discussed in a later chapter | ||
| Mixing `string` and string literals in one union | The literals vanish into `string` | Remove the wider type |
Decision guidance
Reach for a union when a value really can be one of a small, known set of alternatives, such as an input that accepts a number or a numeric string, a result that is a value or null, or an event that is one of several shapes. Avoid unions when the alternatives share most of their behavior and you only need one common interface. In that case, a single object type with optional properties or a shared interface is often simpler to use. Avoid very large unions of unrelated types. Every consumer must then handle each case, and error messages become long.
Exercise
Given function f(x: string | number[]) { return x.length; }, why does this compile, and what is the type of x.length? Then say what changes if the parameter is declared as (string | number)[].
Show answer
It compiles because both string and number[] have a length property, so length is available on the union. Its type is number. If the parameter is (string | number)[], x is always an array, so x.length is still number, but the meaning differs: x can no longer be a plain string, and the array items can be strings or numbers.
Exercise
What does the compiler report for this code, and how would you fix it without changing the type of value?
function double(value: string | number): number {
return value * 2;
}
Show answer
It reports an error because the * operator requires a number, and value could be a string. Fix it by narrowing before the arithmetic, for example: if (typeof value === "string") { return Number(value) * 2; } return value * 2;. After the if, the compiler knows value is a number.