Sub topic 1
Union types: a value that is one of several types
Prerequisites
This chapter assumes that you know basic TypeScript syntax, object types, functions, if statements, and switch statements. It also assumes that your tsconfig.json enables strict mode:
{
"compilerOptions": {
"strict": true
}
}A union type describes a value that can have one of several types. Write a union by placing | between the possible types.
type Identifier = string | number;
let userId: Identifier = "user-42";
userId = 42;userId can contain a string or a number. It cannot contain a boolean, object, or other value.
A union is different from an intersection. A union means “this type or that type.” An intersection, written with &, means “this type and that type.” This chapter focuses on unions.
Reading and creating union types
Unions work with primitive types, object types, and literal values.
type SearchKey = string | number;
type Response = { status: 200; body: string } | { status: 404; message: string };A value of type Response must match exactly one of the object shapes. TypeScript does not let you assume that every property exists:
function printResponse(response: Response): string {
// Error: neither object shape guarantees a body property.
// return response.body;
if (response.status === 200) {
return response.body;
}
return response.message;
}The status check narrows the union. Narrowing means reducing a broad type to a more specific type after checking a value at runtime. In the first branch, TypeScript knows that response is the success object. After the check fails, it knows that response is the not-found object.
The compiler uses checks such as these to narrow unions:
typeof value === "string"for primitive typesvalue instanceof SomeClassfor class instances"property" in valuefor object properties- Equality checks such as
value.kind === "circle"
A union of object shapes
Suppose a function accepts either a text message or a numeric message:
type Message =
| { text: string }
| { code: number };
function describe(message: Message): string {
if ("text" in message) {
return `Text: ${message.text}`;
}
return `Code: ${message.code}`;
}
console.log(describe({ text: "Ready" }));
console.log(describe({ code: 503 }));The in operator checks whether a property exists. It is useful when the object shapes have different property names. However, a shared, literal-valued property is often clearer. That property is called a discriminant, or tag. A union that uses such a tag is a discriminated union. Later chapters will use tags for more precise narrowing and exhaustive checks.
How a union flows through a program
A union keeps uncertainty visible until your code handles it.
A union does not automatically convert one type into another. For example, TypeScript will not let you call string methods before checking that a value is a string.
Exercise
Exercise
What is the type of input inside the else branch, and why? function f(input: string | number) { if (typeof input === "string") { return input.length; } else { return input.toFixed(2); } }
Show answer
input is a number. The typeof input === "string" branch handles strings, so TypeScript narrows the remaining union member to number in the else branch.