TypeScript Tuples

TUPLES is the data structure that store element of different data type unlike array.

example of tuple with number and string value:

Destructuring a Tuple

In the above code, x will be assigned as 10 and y will be assigned with “shri”. it destructure the tuple into individuals value shown above.

summary of some common operations on Tuples in TypeScript:

OperationDescription
Access elementsTuples elements can be accessed by index. Example: let myTuple: [string, number] = [“Hello”, 42]; console.log(myTuple[0]); // Outputs: “Hello”
Add elementsNew elements can be added to a tuple using the assignment operator. Example: myTuple[2] = true;
Update elementsExisting elements can be updated using the assignment operator. Example: myTuple[1] = 33;
Tuple lengthThe length of a tuple is determined by the number of elements in the tuple, and it cannot be changed. Example: console.log(myTuple.length); // Outputs: 2
DestructuringTuples can be destructured into separate variables. Example: let [greeting, numberOfThings] = myTuple;

Note: Tuples in TypeScript are fixed-length and strongly-typed arrays, where the elements have specific types.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top