Syntax
The example below declares a tuple to hold string and number data types in the index.ts file.
//Declare the tuple
let student: [string, number];
// Initialize the tuple
student = ["Ninja", 10];
console.log(student);
Output:
["Ninja", 10]
Note: Though tuples look like pairs, their values aren't stored as pairs per index but rather, the index for each value determines it.
Accessing elements in a tuple
For accessing an element in a tuple, we use its index just like an array.
Let student: [string, number] = ['Ninja', 10];
console.log(student[0]);
console.log(student[1]);
We can create dictionaries and key-value pairs when we use tuples. We can now have an array of students and their roll number without passing in a different type of information, causing problems in the future.
let student: [string,number][] = [['Ninja_1', 10],['Ninja_2',11],['Ninja_3', 12]];
To assign a value to a tuple, its first two members must have the same type as the types defined in the tuple.
If we pass an incorrect data type to the tuple, such as the example below where we change the option's value to [10, "Ninja"], the typescript compiler will throw an error.
// Declare the tuple
let student: [string, number];
// Initialize the tuple
student = ["Ninja", 10];
// Incorrect order of value
student = [10, "Ninja"];
Error:
// Type 'number' is not assignable to type 'string'.
// Type 'string' is not assignable to type 'number'.
Tuple Operations
Many operations can be done with TypeScript's tuples, like pushing a new item with push(), removing an item with pop(), etc.
push()
It adds an item at the end of the tuple.
let student = ["Ninja",10];
console.log("Before using push() "+ student) // returns the student array
student.push('typescript') // append value to the student tuple
console.log("After using push() "+student)
Output:
"Before using push() Ninja,10"
"After using push() Ninja,10,typescript"
pop()
It removes and returns the value from the end of the tuple.
console.log("Before using pop() "+student)
console.log(student.pop()+" removed from the student tuple") // removes and returns the last item
console.log("After using pop() "+student)
Output:
"Before using pop() Ninja,10,typescript"
"typescript removed from the student tuple"
"After using pop() Ninja,10"
Updating Tuples
Changing a tuple is possible. This means that you can update or modify the values of the elements in a tuple.
let student = ['Ninja', 10]; //create a tuple
console.log("Value at index 1 before updating: "+student[1])
//update a tuple element
student[1] = 11
console.log("Value at index 1 after updating:"+student[1])
Output:
"Value at index 1 before updating: 10"
"Value at index 1 after updating:11"
Destructuring a Tuple
When you destroy a body, you destroy its structure. Destructuring comes into play with TypeScript when used in the context of a tuple.
let student = ['Ninja', 10, 'typescript'];
let [value1,value2]=student;
console.log(value1,value2);
Output:
"Ninja", 10
Clear the fields of a Tuple
It is possible to clear fields, but we cannot delete tuple variables. An empty tuple fieldset can be assigned to a tuple to clear its fields.
let student = ['Ninja', 10, 'typescript'];
student = [];
console.log(student);
Output:
[ ]
Passing Tuple to Functions
We can also pass tuples to functions in typescript.
let student = ["Ninja", 10, "typescript"];
//Passing tuples in function
function show(values:any[]) {
for(let i = 0;i<student.length;i++) {
console.log(student[i]);
}
}
//Calling tuple in function
show(student);
Output:
“Ninja"
10
"typescript"
Frequently Asked Questions
Q1. What are the advantages of using tuple in TypeScript?
Ans 1: The tuple type of TypeScript corresponds to an array with a fixed number of elements. Our container can store multiple types of values in a fixed size, where the order and structure of the values are essential. This data type might be the most useful when we are sure exactly how many types in an array we want to allow.
Q2. How is a tuple different from an array?
Ans 2:
- In the case of tuples, which work like arrays and have the same methods as arrays, why can't we use an array of type 'any' to achieve the above examples?
- In short, yes, you can, but then specific values which you do not want in your array will be allowed in.
- You can hold multiple types of data in your array using a tuple and set constraints for your array.
Q3. What is any type in TypeScript?
Ans 3: It allows us to assign literally "any" particular value to a variable, simulating pure JavaScript the way types can be dynamically assigned from other types, such as Strings becoming numbers.
Key-Takeaways
Our productivity and developer experience is greatly enhanced by TypeScript. As shown, integrating it with an existing JavaScript project is simple and carries very little overhead. TypeScript and JavaScript are not in competition with each other.
Rather than replacing JavaScript, TypeScript was created to complement it. They may become very similar in features in the future, with TypeScript remaining the statically-typed alternative. Our introduction to TypeScript tuples barely scratches the surface of what TypeScript is capable of.
If you are want to pursue a new career in Web Development, we suggest you get your fundamentals clear with our Full Stack Development course.
Thanks for reading!