In TypeScript, a tuple is a type of array that allows you to specify the type and order of each element. This means that you can define an array where each element has a specific type, and you can enforce that the elements are in a specific order.
Declaration
Here's an example of how to declare a tuple in TypeScript:
let person: [string, number] = ["Alice", 30];
In this example, the variable person
is declared as a tuple with two elements. The first element is a string that represents the person's name, and the second element is a number that represents the person's age.
Accessing the Values
Using Square Brackets
You can access individual elements of a tuple using square brackets and the element's index:
let person: [string, number] = ["Alice", 30];
console.log(person[0]); // Output: "Alice"
console.log(person[1]); // Output: 30
Via Destructuring
You can also use destructuring to extract individual elements of a tuple into separate variables:
let person: [string, number] = ["Alice", 30];
let [name, age] = person;
console.log(name); // Output: "Alice"
console.log(age); // Output: 30
More than Two Elements
You can also define a tuple with any number of elements, as long as each element has a specific type:
let data: [string, number, boolean] = ["hello", 42, true];
Sample Usage
Tuples can be useful when you need to work with collections of data where each element has a specific type and order. For example, you might use a tuple to represent a date in the format [year, month, day]
, or to represent a point in two-dimensional space in the format [x, y]
.
let date: [number, number, number] = [2022, 3, 1]; // March 1, 2022
let point: [number, number] = [10, 20]; // x = 10, y = 20
One important thing to note is that while tuples provide more type safety than regular arrays, they can also be more restrictive. If you try to assign an element of the wrong type or in the wrong order, you'll get a compile-time error. So be sure to define your tuples carefully to avoid errors.
View Parent Post: TypeScript: Everything You Need to Know