Declare an Array with Fixed length in TypeScript

avatar

Borislav Hadzhiev

Tue Mar 01 20223 min read

banner

Photo by Lê Tân

Declare an Array with Fixed length in TypeScript #

Use a tuple to declare an array with fixed length in TypeScript, e.g. const arr: [string, number] = ['a', 1]. Tuple types allow us to express an array with a fixed number of elements whose types are known, but can be different.

index.ts
// ✅ Array of Fixed length let arr: [string, number, number]; arr = ['coords', 10, 5]; // ⛔️ Error: Type '[string]' is not // assignable to type '[string, number, number]'. arr = ['a']; // ✅ Create array of N empty elements // (however, you can change array's size) // 👇️ const arr2: any[] const arr2 = new Array(4); console.log(arr2); // 👉️ [, , ,] console.log(arr2.length); // 👉️ 4

We declared a tuple with 3 elements with types of string, number and number.

If you try to re-declare the arr variable to an array that doesn't contain 3 elements, you'd get an error.

If you add the correct number of elements to the array, but mix up the types, you'd also get an error.

index.ts
let arr: [string, number, number]; arr = ['coords', 10, 5]; // ⛔️ Error: Type 'string' is not // assignable to type 'number'.ts(2322) arr = ['a', 10, 'b'];

The tuple type is used to express an array with fixed number of elements whose types are known, but can be different.

Having said that, tuples are represented by an array, and you are still able to call the push() method to add an element to the tuple.

index.ts
const arr: [string, number, number] = ['coords', 10, 5]; // ✅ Ok arr.push('hello'); // 👇️ ['coords', 10, 5, 'hello'] console.log(arr);

If you want to prevent this from happening, you can declare the tuple as readonly.

index.ts
const arr: readonly [string, number, number] = ['coords', 10, 5]; // ⛔️ Error: Property 'push' does not exist // on type 'readonly [string, number, number]'.ts(2339) arr.push('hello');

But this also means that you aren't able to change the values of the tuple's elements.

index.ts
const arr: readonly [string, number, number] = ['coords', 10, 5]; // ⛔️ Cannot assign to '0' because // it is a read-only property.ts(2540) arr[0] = 'hello'

Tuples are useful, because when accessing a tuple at an existing index, TypeScript knows the type of the value.

index.ts
const arr: [string, number, number] = ['coords', 10, 5]; console.log(arr[0].toUpperCase()); // 👉️ "COORDS" console.log(arr[1].toFixed(2)); // 👉️ "10.00"

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

index.ts
const arr: [string, number, number] = ['coords', 10, 5]; // ⛔️ Tuple type '[string, number, number]' of // length '3' has no element at index '3'.ts(2493) console.log(arr[3]);

If you need to declare an array that has a max length of X, use a tuple with optional values.

index.ts
// ✅ Array of Max length let arrOfMaxLength3: [string?, string?, string?] = []; arrOfMaxLength3 = ['a', 'b', 'c']; // ✅ OK arrOfMaxLength3 = ['a', 'b']; // ✅ OK arrOfMaxLength3 = ['a']; // ✅ OK // ⛔️ Error: Source has 4 element(s) but target allows only 3. arrOfMaxLength3 = ['a', 'b', 'c', 'd'];

The question mark is used to mark the values in the tuple as optional. The tuple in the example can have a maximum of 3 elements (unless you use array methods to add more).

If you need to declare an array that has a min length of X, use this approach.

index.ts
let arrOfMin2: [string, string, ...string[]] = ['a', 'b']; arrOfMin2 = ['c', 'd'] // ✅ OK // ⛔️ Error: Source has 1 element(s) // but target requires 2.ts(2322) arrOfMin2 = ['c']

The array can have a minimum of 2 elements of type string (unless you use an array method to remove an element).

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