0Pricing
TypeScript Academy · Lesson

Union and Intersection Types

Combine and work with multiple types.

1

Union and Intersection Types

Welcome to the next lesson! In this lesson, you’ll learn how to use union types to allow multiple possible types for a variable and intersection types to combine multiple types into one. These are powerful tools for creating flexible and robust code. Let’s get started!

Union and Intersection Types — illustration 1

2

What Are Union Types?

Union types let a variable hold more than one type. You can use the | symbol to define a union type.

Example: A variable that can be either a string or a number:

Task: Declare a variable with a union type and assign different values to it.

let value: string | number;
value = "Hello";
console.log(value); // Output: "Hello"

value = 42;
console.log(value); // Output: 42

All lessons in this course

  1. Arrays and Tuples
  2. Union and Intersection Types
  3. Enums
  4. Literal Types
← Back to TypeScript Academy