TypeScript provides various features to enhance type safety and developer productivity. One of these features includes Object Tuple Types. This feature ensures that an object follows a consistent shape in our code which results in a reduction in runtime errors and improves code quality.
What are Object Tuple Types?
- Object Tuple Types allow us to define structured objects with a fixed number of properties, each with a specific data type.
- Object Tuple Types in TypeScript are a way to define the structure of objects as a tuple. A tuple is an ordered list of elements and in TypeScript, a Tuple represents an object with a specific number of properties i.e. have a fixed length, each index having a predefined data type.
- Unlike JavaScript objects, Object tuple types have a fixed structure.
- Tuple types in TypeScript are designed to have a fixed and specific structure with a predefined number of elements and data types. Therefore, the TypeScript compiler enforces that you provide all the expected values during object creation.
- If we don’t provide all the expected values while creating an object of a Tuple type in TypeScript, we will get a compilation error.
Syntax:
type TupleTypeName = [Type1, Type2, ...];
Where –
- TupleTypeName: The name you assign to the tuple type.
- Type1, Type2, …: The data types of each property in the tuple.
Tuple Array
- In Tuple Array, we create an array of tuple types.
- Here, Tuple Types represent a sequence of elements having a fixed structure and each element has its own specific predefined data type.
- This can ensure that each tuple in the array has a specific structure(length and property).
- This can allow us to maintain a collection of data structure.
Example: Here, we declared a tuple type item first and then we created an array of Products of item[] tuple type.
type item = [string, number]; let Products: item[] = [ [ "Laptop" , 999],
[ "Smartphone" , 599],
[ "Tablet" , 299],
]; console.log(Products); |
Output:
[ [ 'Laptop', 999 ], [ 'Smartphone', 599 ], [ 'Tablet', 299 ] ]
Destructure Tuple
- Destructuring is a feature that allows us to break the tuple and assign the tuple values to different variables.
- This feature allows easier access to tuple values after extracting and assigning them to a variable from the tuple.
- If you want to know about destructing in depth please refer to this article: How tuple destructuring works in TypeScript?
Example: Here, we declare a type Triangle create a variable of type Triangle and assign the values to the tuple. To Destructure this tuple and get the values into individual elements, we create variables in this form [a, b, c], so the values will assigned in this manner: let a=10, b=20, c=30.
// Define a triangle tuple type type Triangle = [number, number, number]; // Create a triangle variable of Type Triangle let triangle: Triangle = [10, 20, 30]; // Destructure the tuple into individual variables a, b, c let [a, b, c] = triangle; // Calculate the perimeter of the Triangle let perimeter = a + b + c; console.log(`Perimeter of triangle with sides ${a} ,${b}, ${c} : ${perimeter}`);
|
Output:
Perimeter of triangle with sides 10 ,20, 30 : 60
Optional Tuple
- In Optional Tuple, We can make a property optional, which means this property may or may not be present in the tuple.
- This feature provides us great flexibility while writing code as in tuple type we have a fixed length and all properties are mandatorily required while creating a variable of tuple type.
- But using this feature, we can make a property of tuple type optional.
Example: In this example we have made the number property optional, so while creating a variable of mentor type. the age property may be present or may not be present.
// Define an optional tuple type for a Mentor type Mentor = [string, number?]; // Create a mentor with an optional age let Mony: Mentor = [ "Mony" ];
let Lala: Mentor = [ "Lala" , 21];
console.log(Mony); // [ 'Mony' ]
console.log(Lala); // [ 'Lala', 21 ]
|
Output:
[ 'Mony' ]
[ 'Lala', 21 ]
Tuple with Rest Elements
- A tuple with rest elements allows us to capture additional values in an array at the end of the tuple.
- This is particularly useful when we want to define a tuple with a fixed number of known elements followed by a rest element that captures additional elements of the same type.
- We can only collect values of the same data type in the rest elements.
- It’s a powerful feature in TypeScript for creating dynamic lists of elements while preserving type safety.
Example: In this example, we created a rest element of type number, a dynamic list, which can hold any number of values passed in the tuple but only of number type. we are trying to track gaming scores.
type GameScores = [string, number, ...number[]]; let CricketScores: GameScores = [ "Dhoni" , 50, 75, 90, 65, 80];
console.log(CricketScores); |
Output:
[ 'Dhoni', 50, 75, 90, 65, 80 ]
Tuple with Rest Parameters and Arguments
We can use tuple types with rest parameters and rest arguments to handle functions that take a variable number of arguments while preserving type safety.
Example: Let’s consider this example, here we have a tuple type with properties string, number, …string[] (can hold any number of string values, it is a dynamic list). Function call happens with the… spread operator which separates each property into individual variables and in the function parameter, this is handled by the rest parameter.
function printMembersNameandSkills(...details: [string, number,
...string[]]) { for (let i = 0; i < details.length; i++) {
if (i == 0) console.log(`Name : ${details[i]}`);
if (i == 1) console.log(`E-ID : ${details[i]}`);
else console.log(`Skills : ${details[i]}`);
}
} type member = [string, number, ...string[]]; let gfgTeamMembers: member = [ "Roland" , 1234,
"Java" , "C#" , "Python" , "TypeScript" ];
printMembersNameandSkills(...gfgTeamMembers); |
Output:
Name : Roland
Skills : Roland
E-ID : 1234
Skills : Java
Skills : C#
Skills : Python
Skills : TypeScript