Type an Array with a Union type in TypeScript


Borislav Hadzhiev

Last updated: Mar 2, 2022


Photo from Unsplash

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.

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.

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 parentheses, e.g. (string | number)[] and not string | number[], which has a different meaning.

// ⛔️ 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.

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.