How To Declare An Array With Fixed Length In TypeScript

Declare an Array with Fixed length in TypeScript

There are many cases where we would have to declare an array with fixed length in TypeScript. If you are still confused and don’t know how to do so, don’t worry because, in this tutorial, we will describe different methods to do this task.

Declare an array with fixed length in TypeScript

Example 1:

We have a sum function and try to call it on an array.

function sum(a: number, b: number, c: number, d: number): any {
	return a + b + c + d;
}

var myArr = [23, 54, 98, 22];
var result = sum(...myArr);
console.log(result);

Output: 

A spread argument must either have a tuple type or be passed to a rest parameter.

So the problem here is that we are using a spread syntax (…), which will expand our array more than its original elements. Therefore, when we use it on a fixed-parameters function, we will get this error. That is why we need to declare an array with fixed length. Here are some possible ways to do so:

Using the tuple type

The tuple allows you to set the length of the array.

var myArr: [type, type,...] = [value, value,...];

For example: 

var myArr: [number, number, number, number] = [1, 2, 3, 4];

JavaScript will understand that we are creating a four-parameter tuple and its length is fixed. 

So let’s use it to try to solve our example 1: 

function sum(a: number, b: number, c: number, d: number): any {
    return a + b + c + d;
}

var myArr: [number, number, number, number] = [23, 54, 98, 22];
var result = sum(...myArr);
console.log(result);

Output: 

197

Readonly tuple()

Although we have set the array as tuple, we can still use the push() method to add elements to the tuple. For example: 

var myArr: [number, number, number, number] = [23, 54, 98, 22];
myArr.push(67);
console.log(myArr);

Output: 

[23, 54, 98, 22, 67] 

To prevent this, we can always set the tuple to ‘readonly‘.

var myArr: readonly [number, number, number, number] = [23, 54, 98, 22];
myArr.push(67);

console.log(myArr);

Output: 

Property 'push' does not exist on type 'readonly [number, number, number, number]'.

The ‘readonly‘ means that you can access the elements of the array but cannot make any changes.

Summary

In this tutorial, we have shown you how to declare an array with fixed length in TypeScript. The idea is to type our array as a tuple and set it to ‘readonly‘ mode. Let’s try them to get your desired results.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *