Course contentsShow
← TypeScript
Lesson 109 of 1,7963. Basic TypesFree lesson

Arrays of Union Types

Creating arrays that hold multiple different types using union element types.

Arrays of Union Types

In this lesson, you'll learn how to create arrays that can hold multiple different types of elements using union types.

What Are Arrays of Union Types?

Up until now, you've learned that arrays in TypeScript hold a single type of element—like number[] for an array of numbers or string[] for an array of strings. But what if you need an array that can store both numbers and strings? That's where arrays of union types come in.

By combining arrays with union types (which you learned about earlier), you can create flexible collections that hold values of different types.

The Syntax

To create an array that can hold multiple types, wrap your union type in parentheses before adding the array brackets:

let mixed: (number | string)[] = [1, "hello", 42, "world"];

This reads as: "an array where each element is either a number or a string."

Think of It Like a Mixed Container

Imagine a storage box labeled "Numbers or Strings Only." You can put number cards or word cards inside, but nothing else. That's exactly what (number | string)[] does—it ensures each item is valid, while still allowing variety.

let flexible: (boolean | null)[] = [true, null, false, null];

This array can hold boolean values or null, but nothing else.

Why Use Arrays of Union Types?

Sometimes data naturally comes in mixed forms—like API responses that return either error codes (numbers) or error messages (strings). Arrays of union types let you model this reality while keeping type safety intact.

Key Takeaway: Arrays of union types let you store multiple different types in a single array by using (Type1 | Type2)[] syntax, maintaining type safety while allowing flexibility.