Sub topic 1
Union types: a value that is one of several types
A union type says that a value is exactly one of a fixed list of types, but the compiler may not know which one at a given point in the code. Discriminated unions, the subject of this tutorial, are built on this feature. This chapter covers how plain unions behave: what you may do with them, what you may not, and where the surprises are.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript syntax: type annotations, type aliases, interfaces, and functions.
- Object types and optional properties.
ifandswitchstatements.- That your
tsconfig.jsonhas"strict": true. Several examples depend onstrictNullChecks, which strict mode turns on.
What a union type is
You write a union with the | operator between two or more types. Each type in the list is a member of the union.
function format(id: string | number): string {
return `ID-${id}`;
}
console.log(format(7));
console.log(format("abc"));The parameter id accepts any value of type string or type number. Passing a boolean is a compile error.
You can give a union a name with a type alias, which is how you will usually see it:
type Id = string | number;
let userId: Id = "u-100";
userId = 100;Think of a union as a set of possible values. string | number contains every string and every number. A type is assignable to a union if it is assignable to at least one member. The reverse does not hold: a string | number value cannot go where a plain string is required, because it might be a number.
const a: string | number = "x"; // OK: string is a member
// const b: string = a; // Error only if a were not narrowed; see belowThe second line is commented out because of an edge case covered later in this chapter. TypeScript narrows a to string at that point, so the assignment would in fact compile.
You can only do what every member allows
When the compiler does not know which member you hold, it allows only operations that are valid for all members.
function show(id: string | number): string {
return id.toString(); // OK: both string and number have toString
}
function lengthOf(id: string | number): number {
// return id.length; // Error: Property 'length' does not exist on type 'number'
return String(id).length;
}This rule keeps you safe. A number has no length, so reading it would produce undefined at runtime. The compiler stops you before that happens.
Narrowing: asking which member you have
To use a member-specific operation, you first check which member you hold. This is called narrowing: inside the checked branch, the compiler treats the value as the smaller type. The typeof operator is the most common check for primitive types.
function pad(id: string | number): string {
if (typeof id === "string") {
return id.padStart(5, "0"); // id is string here
}
return id.toFixed(0).padStart(5, "0"); // id is number here
}
console.log(pad("42"));
console.log(pad(7));After the if returns, TypeScript removes string from the possibilities, so the last line sees number. The next chapters study narrowing in detail. For now, remember the pattern: a union forces you to check before you use.
Narrowing by assignment
A variable declared with a union type has the declared type, but assigning a value narrows it to the assigned type until the next assignment.
let value: string | number = "hello";
console.log(value.toUpperCase()); // OK: narrowed to string by the assignment
value = 42;
console.log(value.toFixed(1)); // OK: narrowed to numberThis explains the earlier const b: string = a example. It also catches people out in reverse. Narrowing from assignment resets inside callbacks and after function calls that could reassign a let variable, so the compiler may forget the narrowed type there.
Unions of object types
Unions are not limited to primitives. Members can be object types, which is the case that matters for discriminated unions.
type Circle = { radius: number; color: string };
type Square = { size: number; color: string };
type Shape = Circle | Square;
function colorOf(shape: Shape): string {
return shape.color; // OK: both members have color
}
function sizeOf(shape: Shape): number {
// return shape.radius; // Error: Property 'radius' does not exist on type 'Square'
return "radius" in shape ? shape.radius : shape.size;
}Only the shared property color is accessible without a check. The in operator narrows by testing whether a property exists on the value. It works, but it is fragile: if you later add a radius property to Square, the check silently stops distinguishing the two. A dedicated tag property avoids this problem, and that is the idea the rest of the tutorial develops.
Unions with null and undefined
Under strictNullChecks, null and undefined are separate types, so "maybe missing" is expressed as a union.
function lengthOrZero(text: string | null): number {
return text === null ? 0 : text.length;
}
function greet(name?: string): string {
// name has type string | undefined
return `Hello, ${name ?? "stranger"}`;
}
console.log(lengthOrZero(null));
console.log(greet());An optional parameter or optional property adds undefined to its type automatically. Forgetting the check on such a value is the most common union error in real code.
Placement of the union: array edge cases
Where you put the | changes the meaning. These two types are different:
const mixed: (string | number)[] = [1, "a", 2]; // each element is string or number
const uniform: string[] | number[] = [1, 2, 3]; // the whole array is one kind
// const broken: string[] | number[] = [1, "a"]; // Error: mixed contents not allowed
console.log(mixed.length, uniform.length);(string | number)[] is an array whose elements vary. string[] | number[] is either an all-string array or an all-number array. Reading from the second type needs more care, because you must first find out which array you have.
How the compiler simplifies unions
The compiler normalizes unions, so some written forms collapse:
| Written type | Result | Reason | Column |
|---|---|---|---|
| `string \ | string` | `string` | Duplicates are removed. |
| `string \ | "a"` | `string` | The literal `"a"` is already a subset of `string`. |
| `string \ | never` | `string` | `never` has no values, so it adds nothing. |
| `string \ | unknown` | `unknown` | `unknown` contains every value. |
| `string \ | any` | `any` | `any` absorbs everything and disables checking. |
The order of members never matters: string | number and number | string are the same type. The string | "a" collapse has a practical consequence. If you want editor autocomplete for suggested literals while still accepting any string, plain string | "a" will not give it to you, because the literal disappears.
Common errors
- Using a member-specific property without narrowing. The message "Property 'x' does not exist on type 'A | B'" means you need a check first.
- Assuming
inortypeofcan tell apart any two types.typeofreturns only a small set of strings ("string","number","object", and so on). It cannot separate two object types, andtypeof nullis"object". - Using
anyto silence the error. This removes the checking you gained from the union. Use narrowing orunknownplus a check instead. - Forgetting that a union return type pushes the check onto every caller. A function that returns
string | nullmakes each caller handlenull. That is usually the point, but it costs code at each call site.
Summary of working rules
- A union type holds a value of exactly one member at a time.
- Without a check, you may use only what all members share.
- Narrow with
typeof, equality,in, or assignment to get at member-specific operations. - Treat
nullandundefinedas union members, and check for them. - Watch where the
|sits relative to array brackets.
Exercise
Given type Input = string | string[], write a function toList(input: Input): string[] that returns the array unchanged when given an array, and wraps a single string in a one-element array. Which check do you use to narrow, and why does typeof not work here?
Show answer
Use Array.isArray:
function toList(input: string | string[]): string[] {
return Array.isArray(input) ? input : [input];
}
typeof input === "object" would also be true for arrays, but it cannot be used safely as a general rule for object types because typeof null is also "object". More importantly, typeof input === "string" works here as an alternative, since the only non-string member is an array. Array.isArray is clearer because it states the intent and narrows the other branch to string.
Exercise
What are the types of x and y below, and does the last line compile? Explain.
let x: string | number = "hi";
let y: (string | number)[] | string[] = ["a"];
console.log(x.toUpperCase());
y = [1, "b"];
Show answer
x is declared as string | number but narrowed to string by the assignment, so x.toUpperCase() compiles. y is declared as a union of (string | number)[] and string[]. The final assignment y = [1, "b"] compiles, because [1, "b"] is assignable to (string | number)[], which is a member of the union. This differs from string[] | number[], which would reject the mixed array.