Arrays of Union Types
What you'll learn: How to create arrays that can hold multiple different types using union syntax with arrays.
The Core Idea
Sometimes you need an array that can contain values of different types. In TypeScript, you can combine union types (which you just learned) with array types to allow a single array to hold a mix of values.
There are two equivalent syntaxes:
Array<A | B>— using the generic Array type(A | B)[]— using bracket notation with parentheses
Both create the exact same type: an array where each element can be type A or type B.
Basic Syntax
// These two are identical:
let mixed: Array<string | number>;
let alsoMixed: (string | number)[];
mixed = [1, "hello", 42, "world"]; // ✓ Valid
alsoMixed = ["test", 100, 200, "data"]; // ✓ Valid
Notice the parentheses in (string | number)[]? They're crucial. Without them, string | number[] means "a string OR an array of numbers" — completely different!
Why This Matters
Arrays of union types let you model real-world data that naturally contains mixed types:
let responses: (string | number)[] = [];
responses.push("Success"); // ✓ Valid
responses.push(404); // ✓ Valid
responses.push(true); // ✗ Error: boolean not in union
Each element in the array is checked individually against the union type, giving you type safety while maintaining flexibility.
Key Takeaway: Use Array<A | B> or (A | B)[] to create arrays holding multiple types, and always remember the parentheses in the bracket syntax to group the union correctly.