TS Tuples
Tuples in TypeScript allow you to define an array with a fixed number of elements where each element can have a specific type. This provides type safety when working with arrays of mixed data types.
Key Topics
Defining Tuples
Tuples are defined using the [type1, type2, ...]
syntax, where each type corresponds to an element in the tuple.
let user: [string, number];
user = ["Alice", 25];
console.log(user[0]); // Alice
console.log(user[1]); // 25
Output
Alice
25
Explanation: The tuple user
must contain a string
followed by a number
. Accessing elements uses array-like indexing.
Tuple Operations
Tuples support common array operations such as adding and removing elements, but type safety applies to the defined elements.
let employee: [number, string] = [101, "Bob"];
employee.push("Developer");
console.log(employee); // [101, "Bob", "Developer"]
Output
[101, "Bob", "Developer"]
Explanation: Additional elements can be added to tuples, but they do not extend the original tuple's type definition.
Tuples with Labels
You can define tuples with labels for better readability and maintainability.
type Employee = [id: number, name: string];
let employee: Employee = [101, "Charlie"];
console.log(employee[0]); // 101
console.log(employee[1]); // Charlie
Output
101
Charlie
Explanation: Using labeled tuples helps clarify what each element represents, enhancing code readability.
Key Takeaways
- Type Safety: Tuples ensure each element has the correct type and position.
- Flexibility: You can perform array operations while adhering to the tuple's type definition.
- Labeled Tuples: Enhance readability and make the tuple's purpose clear.