In TypeScript, a tuple is a special array-like data structure that allows you to store values of different types with a fixed number of elements. You can define a tuple by providing the types of its elements in a specific order within square brackets, separated by commas. Once you declare the types of the elements, the order becomes important, and you cannot add more elements than the defined tuple length.
Here is an example of a tuple in TypeScript:
let tupleExample: [string, number, boolean];
tupleExample = ["TypeScript", 2021, true]; // This is a valid tuple assignment
In this example, ‘tupleExample‘ is defined to have exactly three elements: a ‘string‘, a ‘number‘, and a ‘boolean‘. The order of these elements in the tuple is important. For example, if you try to assign different types in a different order, TypeScript will throw a compile-time error:
tupleExample = [2021, "TypeScript", true]; // This would cause a compile-time error
Another feature of tuples in TypeScript is that you can access and manipulate their elements using indexing, just like you would do with regular arrays:
console.log(tupleExample[0]); // Output: "TypeScript"
tupleExample[1] = 2022; // Update the number value in the tuple
However, you cannot add more elements to a tuple than its declared length:
tupleExample[3] = "New element"; // This would cause a compile-time error
In summary, tuples in TypeScript provide a way to define fixed-length, ordered collections of values with different types, enabling strict compile-time checks on the structure of the data being represented.