A tuple allows you to store a fixed number of elements with different types in a specific order.
Example:
// Declare a tuple type
let x: [string, number];
// Initialize it correctly
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error: Type 'number' is not assignable to type 'string' and vice versa
Key Points:
-
Fixed Types: Each element in a tuple has a specific type in the order you define. The first element is expected to be a
string
, and the second anumber
.x = ["hello", 10];
is valid because the types match.x = [10, "hello"];
is invalid because the types are swapped.
-
Accessing Elements: You can access elements by index:
console.log(x[0].substring(1)); // OK, string method on a string console.log(x[1].substring(1)); // Error, number doesn't have 'substring'
-
Length is Fixed: Tuples have a fixed length and type structure.
- Attempting to assign values to indices outside the defined range will result in an error.
x[3] = "world"; // Error: Property '3' does not exist on type '[string, number]' console.log(x[5].toString()); // Error: Property '5' does not exist on type '[string, number]'