Tuples in TypeScript
Job-ready Online Courses: Click for Success - Start Now!
TypeScript is a statically-typed programming language that builds on top of JavaScript by adding optional static typing, classes, interfaces, and other features. One of the features introduced by TypeScript is the concept of Tuples.
A tuple is an ordered list of elements, where each element may have a different type. Tuples in TypeScript are similar to arrays, but the types of the elements in a tuple are fixed and cannot be changed once the tuple is defined.
Using tuples can help catch errors at compile-time by enforcing the correct order and types of elements in a list. Tuples can also be used to define the return type of a function or the type of a variable that holds a fixed set of values.
In TypeScript, you can define a tuple using square brackets, where a comma separates each element. Here’s an example:
let DataFlair_myTuple: [string, number]; DataFlair_myTuple = ['hello', 123];
In this example, we have defined a tuple with two elements: a string and a number. We have assigned the tuple a value of “hello” and 123.
Tuples can also be used as return types for functions. Here’s an example:
function DataFlair_getPerson(): [string, number] {
return ['John', 30];
}
let person: [string, number] = DataFlair_getPerson();
console.log(person[0]); // output: John
console.log(person[1]); // output: 30
In this example, we have defined a function called DataFlair_getPerson that returns a tuple with two elements: a string and a number. We have then assigned the returned tuple to a variable called person and used array indexing to access the individual elements.
Tuples can also be used with optional and rest elements. Here’s an example:
let DataFlair_myTuple: [string, number, boolean?]; DataFlair_myTuple = ['hello', 123]; let [a, b, c] = DataFlair_myTuple; console.log(a); // output: hello console.log(b); // output: 123 console.log(c); // output: undefined
In this example, we have defined a tuple with three elements; the third element is optional. We have assigned the tuple a value of “hello” and 123 but have not provided a value for the optional element. We have then used destructuring to assign the individual elements to variables.
Tuples can also be used with rest elements. Here’s an example:
let DataFlair_myTuple: [string, number, ...boolean[]]; DataFlair_myTuple = ['hello', 123, true, false]; console.log(DataFlair_myTuple[2]); // output: true console.log(DataFlair_myTuple[3]); // output: false
In this example, we have defined a tuple with two mandatory elements (a string and a number) and a rest element, an array of booleans. We have assigned the tuple a value of “hello,” 123, true, and false.
Readonly Tupple
In TypeScript, a readonly tuple is a tuple whose elements cannot be modified after creation.
To define a readonly tuple, the readonly keyword can be used before the tuple type annotation:
let DataFlair_person: readonly [string, number] = ['John Doe', 30];
Once a readonly tuple has been defined, its elements cannot be modified directly or through any method or operation. For example, attempting to modify the elements of the DataFlair_person tuple defined above will result in a TypeScript error:
DataFlair_person[0] = 'Jane Doe';
Using readonly tuples can help ensure that the data in a tuple remains immutable, preventing unintended modifications and improving the stability and reliability of a program.
Destructuring Tupple
This is a feature that allows you to extract individual elements from a data structure, such as an array or a tuple, and assign them to separate variables.
Destructuring a tuple involves specifying variable names inside square brackets that match the order and number of elements in the tuple. For example, consider the following tuple:
let DataFlair_person: [string, number] = ['John Doe', 30];
We can use destructuring to extract the individual elements of the tuple and assign them to separate variables as follows:
let [name, age] = DataFlair_person;
In this example, the variable’s name and age are assigned the first and second elements of the DataFlair_person tuple, respectively.
Destructuring can also be used to extract only certain elements of a tuple and skip over certain elements. For example, consider the following tuple with three elements:
let DataFlair_person: [string, number, string] = ['John Doe', 30, 'male'];
To extract only the first and third elements of this tuple and assign them to separate variables, we can use destructuring with commas to skip over the second element:
let [name, , gender] = DataFlair_person;
In this example, the variable’s name and gender are assigned the first and third elements of the DataFlair_person tuple. The second element (the person’s age) is skipped over using a comma in the destructuring assignment.
Destructuring tuples can help simplify code by allowing you to extract and work with individual elements of a tuple without accessing them through their index positions.
Tuple Methods
In TypeScript, tuple methods are functions that operate on tuples. Since tuples are a type of ordered list, tuple methods are similar to array methods in JavaScript but with some differences due to the fixed nature of tuples.
Some common tuple methods in TypeScript include:
1. concat(): Returns a new tuple that combines the elements of two or more tuples.
For Example
var DataFlair_employee: [number, string] = [1, 'Steve'];
DataFlair_employee[1] = DataFlair_employee[1].concat(' Jobs');
console.log(DataFlair_employee);Output
2. slice(): Returns a new tuple that contains a subset of the elements of the original tuple.
For Example
var DataFlair_tup = [11, 89, 23, 7, 98]; var val = DataFlair_tup.slice(2, 4); console.log(val);
Output
3. push(): Adds one or more elements to the end of a tuple and returns the new length of the tuple.
For Example
var DataFlair_tup = [11, 89, 23, 7, 98]; var val = DataFlair_tup.push(4); console.log(val, DataFlair_tup);
Output
4. pop(): Removes the last element of a tuple and returns it.
For Example
var DataFlair_tup = [11, 89, 23, 7, 98]; var val = DataFlair_tup.pop(); console.log(DataFlair_tup);
Output
5. indexOf(): Returns the index of the first occurrence of a specified element in a tuple or -1 if the element is not found.
For Example
var DataFlair_tup = [11, 89, 23, 7, 98]; console.log(DataFlair_tup.indexOf(23));
Output
Conclusion
Tuples can be a powerful tool in TypeScript for enforcing a specific data structure or ensuring a particular order of elements in an array. Tuples have a defined amount of elements. Each element has to be a specified type, making them less flexible than standard arrays.
In conclusion, Tuples are a unique feature of TypeScript that allows you to define an array with a fixed number of elements, where each element can be different. They can represent a specific data structure or enforce a specific order of elements in an array. While they may be less flexible than regular arrays, they can be a powerful tool in TypeScript.
Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

