Define an Array with Multiple types in TypeScript


Borislav Hadzhiev

Last updated: Feb 28, 2022


Check out my new book

Define an Array with Multiple types in TypeScript #

Use a union type to define an array with multiple types in TypeScript, e.g. const arr: (string | number)[] = ['a', 1]. A union type is formed from two or more other types. The array in the example can only contain values of type string and number.

const arr1: (string | number)[] = ['a', 'b', 1, 2];

We used a union type to create an array with multiple types.

You union type can be constructed from as many types as necessary.

const arr1: (string | number | boolean)[] = ['a', 1, true];

If you try to add an element to the array of type that is not compatible with the union, you'd get an error.

const arr1: (string | number)[] = ['a', 1]; // ⛔️ Error: Argument of type '{ hello: string; }' is // not assignable to parameter of type 'string | number'. arr1.push({ hello: 'world' });

You can also use this approach to define an array that contains objects of multiple types.

type Bird = { canFly: boolean; }; type Dog = { canSwim: boolean; }; const bird: Bird = { canFly: true, }; const dog: Dog = { canSwim: false, }; const arr1: (Bird | Dog)[] = [bird, dog]; if ('canFly' in arr1[0]) { console.log(arr1[0].canFly); // 👉️ true } else { console.log(arr1[0].canSwim); }

We have objects of type Bird and Dog with different properties an types. The array can contain elements of the two types.

Notice that we had to use a type guard to be able to access the properties of the objects in the array.

The canFly property is only contained in the Bird type, so we have to make sure that the element in the array is of type Bird before we are able to access the property.

If you have an array that contains multiple types and has a predefined length and order, you can use a tuple.

const arr: [string, number] = ['x', 100];

We've specified that the first element in the array above will have a type of string, and the second a type of number.

Tuple types allow us to express an array with a fixed number of elements whose types are known, but can be different.

This is useful, because if you initialize the array incorrectly you'd get an error.

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

When accessing an element at an existing index, TypeScript knows the type of the value.

const arr: [string, number] = ['x', 100]; // ✅ TypeScript knows first element is string console.log(arr[0].toUpperCase()); // 👉️ "X" // ✅ TypeScript knows second element is number console.log(arr[1].toFixed(2)); // 👉️ 100.00

If you try to access a tuple element at an index that doesn't exist, the type checker throws an error.

const arr: [string, number] = ['x', 100]; // ⛔️ Error: Tuple type '[string, number]' of length '2' // has no element at index '2'.ts(2493) console.log(arr[2]);

If you use the const keyword to declare the tuple, you have to initialize the array with all of the values for which you've specified a type.

// ⛔️ Error: Type '[string]' is not assignable // to type '[string, number]'. // Source has 1 element(s) but target requires 2.ts(2322) const arr: [string, number] = ['x'];

If you don't have all of the necessary values when initializing the array, use the let keyword to declare the tuple.

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.