Type an Array with a Union type in TypeScript

avatar

Borislav Hadzhiev

Wed Mar 02 20222 min read

Type an Array with a Union type in TypeScript #

To type an array with a union type, use parenthesis to wrap the union type, e.g. const arr: (string | number)[] = ['a', 1, 'b', 2];. The array can only contain elements that are members of the union type. Trying to add an element with an incompatible type causes an error.

index.ts
const arr: (string | number)[] = ['a', 1, 'b', 2]; arr.push('c'); // ✅ OK // ⛔️ Error: Argument of type 'boolean' is // not assignable to parameter of type // 'string | number'.ts(2345) arr.push(true);

We declared an array with elements that must conform to a union type.

A union type is formed from combining two or more types and represents values that may be any one of those types.

The array in the example can only contain elements of type string or number.

Your union type can contain as many types as necessary.

index.ts
const arr: (string | number | boolean)[] = ['a', 1, true]; arr.push('c'); // ✅ OK // ⛔️ Type 'string[]' is not assignable // to type 'string'.ts(2345) arr.push(['a', 'b', 'c']);

When using this approach, make sure to wrap the union type in parenthesis, e.g. (string | number)[] and not string | number[], which has a different meaning.

index.ts
// ⛔️ Error: Type 'string' is not // assignable to type 'number'.ts(2322) const arr: string | number[] = ['a', 1];

In the example above, the arr variable can store a string or an array of numbers.

You can also use this approach with classes.

index.ts
class Dog { run() { console.log('dog runs'); } } class Human { walk() { console.log('human walks'); } } class Bird { fly() { console.log('bird flies'); } } // 👇️ array with union type const arr: (Dog | Human)[] = []; const d1 = new Dog(); const h1 = new Human(); arr.push(d1); // ✅ OK arr.push(h1); // ✅ OK const b1 = new Bird(); // ⛔️ Error: Argument of type 'Bird' is not // assignable to parameter of type 'Dog | Human'. arr.push(b1);

We declared an array that contains elements of type Dog or Human.

We can safely add instances of the Dog and Human classes to the array, but trying to add an instance of Bird causes the type checker to error out.

Use the search field on my Home Page to filter through my more than 1,000 articles.