Union Type (TypeScript)

A union type lets a value be one of several types, written with a vertical bar between them, like `string | number`. The value can be any one of the listed types.

TypeScript

Unions model the real-world fact that a value might come in more than one form — an id that is sometimes a number and sometimes a string, or a status that is one of a few specific words.

Before you use a value of a union type in a type-specific way, you often need to narrow it with a type guard (like `typeof x === "string"`) so TypeScript knows which case you're in.

Syntax

type T = A | B | C;

Examples

TypeScript

function format(id: string | number): string {
  return "ID-" + id;
}

console.log(format(42));
console.log(format("x9"));

Output:

ID-42
ID-x9

Learn it in a lesson

See also

Back to the Dictionary