← Back to TypeScript Course | Chapter 5: Type Aliases and Union Types | Lesson 2 of 9

Union Types

A union type allows a value to have one of several possible types. TypeScript uses the | symbol to combine alternatives and helps you safely work with each possibility.

Basic Union Types

A union type is created by placing the | symbol between two or more types, such as string | number. A variable declared with that union type can hold a value matching any one of the listed types, but only one at a time.

Example: Basic Union Types

typescript
let id: string | number;
id = 101;
console.log(id);
id = "abc101";
console.log(id);

Union Types with Objects

Union types can represent entirely different possible object shapes, not just primitives, such as a value that's either a Cat or a Dog object. When the objects in the union have different properties, the union should be narrowed before accessing anything that isn't shared by every member.

Example: Union Types with Objects

typescript
type Cat = { kind: "cat"; meow: () => void };
type Dog = { kind: "dog"; bark: () => void };
let pet: Cat | Dog = { kind: "dog", bark: () => console.log("Woof") };
console.log(pet.kind);

Union Types with Literal Values

A union can also be built from literal values instead of general types, restricting a variable to one of a specific, fixed set of allowed values, like small | medium | large. This is a common and precise way to model options such as status, direction, or size.

Example: Union Types with Literal Values

typescript
let size: 'small' | 'medium' | 'large';
size = 'medium';
console.log(size);

Narrowing a Union

When a value could be any member of a union, TypeScript can narrow it down using runtime checks such as typeof or an equality comparison. Once inside a narrowed branch, TypeScript understands exactly which specific member of the union is currently in play and allows the matching operations.

Example: Narrowing a Union

typescript
function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(0));
  }
}
printId(42);

Union Types in Function Parameters

Union types are extremely common in function parameters when a function is designed to accept several different kinds of input, such as a formatter that handles both string and number values. The function body then narrows the parameter and handles each possible case appropriately.

Example: Union Types in Function Parameters

typescript
function format(value: string | number): string {
  return typeof value === "string" ? value : value.toFixed(2);
}
console.log(format(3.14159), format("hello"));
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.