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
-
Use the
type
keyword to create a new type. - Specify a tuple type using square brackets.
- Inside the square brackets, specify the types for each element in the array.
- Ensure the order and number of types match your desired fixed-length array.
- Declare a variable and assign an array literal to it.
- Now you can access individual elements using index notation.
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