Open In App

How to Declare a Fixed Length Array in TypeScript ?

To declare a Fixed-length Array in TypeScript you can use a Tuple. Tuple types allow you to specify the types for each element in the array and, importantly, define a fixed number of elements in a specific order. In this article, we are going to learn how to declare a fixed-length array in TypeScript.

Syntax

type FixedLengthArray = [Type1, Type2, ..., TypeN]

Approach

Example 1: In this example, FixedLengthArray is a tuple type specifying a fixed-length array with a number, string, and boolean in that order.






type FixedLengthArray = [number, string, boolean];
 
const myArray: FixedLengthArray = [12, 'Geeks', true];
 
const numberValue: number = myArray[0];
const stringValue: string = myArray[1];
const booleanValue: boolean = myArray[2];
 
// Error: Cannot assign to '0'
// because it is a constant.
// myArray[0] = 10;
 
// You can push into tuple but can not access it
// because it is of type 'FixedLengthArray'.
// myArray.push('world');
 
console.log(`Number Value: ${numberValue}`);
 
console.log(`String Value: ${stringValue}`);
 
console.log(`Boolean Value: ${booleanValue}`);

Output:

Number Value: 12
String Value: Geeks
Boolean Value: true

Example 2: In this example, example is a tuple type specifying a fixed-length array with two elements: a string and a number.






type example = [string, number];
 
const myExample: example = ['example', 42];
 
const stringValue: string = myExample[0];
const numberValue: number = myExample[1];
 
console.log(`String Value: ${stringValue}`);
console.log(`Number Value: ${numberValue}`);

Output:

String Value: example
Number Value: 42

Article Tags :