TUPLES is the data structure that store element of different data type unlike array.
example of tuple with number and string value:
1 2 3 |
var demotuples= [10, "shri"] console.log(demotuples[0]) console.log(demotuples[1]) |
Destructuring a Tuple
1 2 |
var demotuples= [10, "shri"] var x,y =demotuples; |
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:
Operation | Description |
Access elements | Tuples elements can be accessed by index. Example: let myTuple: [string, number] = [“Hello”, 42]; console.log(myTuple[0]); // Outputs: “Hello” |
Add elements | New elements can be added to a tuple using the assignment operator. Example: myTuple[2] = true; |
Update elements | Existing elements can be updated using the assignment operator. Example: myTuple[1] = 33; |
Tuple length | The 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 |
Destructuring | Tuples 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.