Heterogeneous Arrays

What

Heterogeneous arrays are arrays that can contain elements of different types. In TypeScript, this is achieved by using union types.

How

You define the array type by wrapping a union of types in parentheses followed by the bracket notation:

// An array that can contain both strings and numbers
let mixedData: (string | number)[] = [1, 2, "three", "four"];

// TypeScript can also infer this automatically
let inferredStyles = [1, 2, "double", "shoto"]; // (string | number)[]

Why

In some scenarios, a collection needs to hold diverse data types. By using a unioned array type, you can model these collections precisely without resorting to the any type, allowing you to safely handle each element using type narrowing during iteration.

Summary

Use unions to keep your collections flexible yet type-safe when they must hold multiple kinds of data.