In TypeScript, a tuple is a finite ordered list of elements with a specific type.
Tuples allow us to express an array where the type of a fixed number of elements is known, but need not be the same.
Type Safety: Typescript ensures that the types of values on specific position of the tuple are consistent with the types defined when the tuple was declared.
Fixed Length: Once a Tuple is defined, the length of a tuple cannot be changed.
Accessing Elements: We can access elements in a tuple using their index value, similar to arrays.
Mixed Types: Tuples allow us to mix various types of values, providing flexibility in how we can structure our data.
They combine elements of different types in a specific order.
let declaredTuple: [string, number, boolean];
Note: This declares a tuple named `declaredTuple` that can hold three values: a string, a number, and a boolean, in that order.
let declaredTuple: [string, number, boolean]; declaredTuple = ["Hi", 22, false];
Here, the tuple is initialized with values that match the specified types and order.
let declaredTuple: [string, number, boolean]; declaredTuple = ["Hi", 22, false]; let greeting: string = declaredTuple[0]; let age: number = declaredTuple[1]; let isActive: boolean = declaredTuple[2];
We can access individual elements in a tuple using their respective indices.
TypeScript can infer tuple types based on the assigned values.
let anotherTuple = ["Hi", 22, false]; // TypeScript infers the tuple type as [string, number, boolean]
let optionalTuple: [string, number?]; optionalTuple = ["Hello"]; optionalTuple = ["Hello", 42];
We can make elements in a tuple optional by using the ? notation.
let readonlyTuple: readonly [string, number] = ["Readonly", 1234]; // readonlyTuple[0] = "Updated"; // Error: Cannot assign to '0' because it is a read-only property
let [first, ...rest] = [1, 2, 3, 4, 5, 6, 7]; console.log(first); // Output: 1 console.log(rest); // Output: [2, 3, 4, 5, 6, 7]
We can make a tuple readonly to prevent modifications.
We can use the rest (we can replace the `rest` variable with any other variable ) using syntax (...) to capture the remaining elements of a tuple.
In Typescript, Tuples provide a way to work with fixed-size collections of heterogeneous data while maintaining type safety when assigning elements.