How to declare a const array in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 16, 2022

banner

Photo from Unsplash

Declare a const array in TypeScript #

Use a const assertion to declare a const array in TypeScript, e.g. const arr = [10, 5] as const. Const assertions enable us to set the elements of an array to readonly, indicating to the language that the type in the expression will not be widened (e.g. from [1, 2] to number[]).

index.ts
// 👇️ const arr: readonly [10, 5] const arr = [10, 5] as const; function multiply(a: number, b: number) { return a * b; } console.log(multiply(...arr)); // 👉️ 50

We used a const assertion to declare a const array.

The multiply function takes exactly 2 arguments of type number, but we have an array containing the 2 numbers.

A const assertion enables us to tell TypeScript that the array can only ever have 2 elements of type number and it's going to be the exact 2 numbers we provided when declaring the array.

The array's type will never be widened, e.g. from [10, 5] to number[].

The array in the example becomes a readonly tuple, so its contents cannot be changed and we are able to safely unpack the two numbers in a call to the multiply function.

You can access the elements of the array just like you would access the elements of any other array.

index.ts
// 👇️ const arr: readonly [10, 5] const arr = [10, 5] as const; console.log(arr[0]); // 👉️ 10 console.log(arr[1]); // 👉️ 5

If you try to change the contents of the array, you would get an error.

index.ts
// 👇️ const arr: readonly [10, 5] const arr = [10, 5] as const; // ⛔️ Error: Property 'push' does not exist on // type 'readonly [10, 5]'. arr.push(15);

We used a const assertion, so the array is now a readonly tuple, whose contents cannot be changed and attempting to do so causes an error during development.

If we try to call the multiply function without declaring the const assertion, we would get an error.

index.ts
const arr = [10, 5]; function multiply(a: number, b: number) { return a * b; } // ⛔️ Error: A spread argument must either have // a tuple type or be passed to a rest parameter. console.log(multiply(...arr)); // 👉️ 50

TypeScript warns us that there is no way of knowing that the contents of the array have not changed between its declaration and the time the multiply function was called.

Had we used a const assertion to declare a const array, TypeScript would know that the array's contents will not change between its declaration and the function invocation.
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.