TypeScript Object Tuple Types
Last Updated :
24 Apr, 2025
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.
JavaScript
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.
JavaScript
// 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.
JavaScript
// 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.
JavaScript
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.
JavaScript
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
Similar Reads
TypeScript Object Types
TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters.Optional properties, denoted with a ? provide flexibility for objects with varying properties. This approach enhances code robustness by
3 min read
TypeScript Object readonly Tuple Types
In this article, we will learn about Object readonly Tuple Types in Typescript. In TypeScript, an object with read-only tuple types is a type that represents an object with properties where each property has a specific value and the order of properties is fixed, just like a tuple. However, unlike re
3 min read
TypeScript Object The Array Type
In TypeScript, the Array Type is used to specify and enforce the type of elements that can be stored in an array, enhancing type safety during development. This adaptability ensures reusability across diverse data types, as exemplified by the Array type (e.g., number[] or string[]). Syntaxlet myArra
2 min read
TypeScript Generic Object Types
TypeScript Generic Object Types allow you to create flexible and reusable type definitions for objects. These generic types can work with different shapes of objects while providing type safety, ensuring your code is both robust and adaptable. They are particularly useful for creating functions or c
3 min read
Explain the Tuple Types in TypeScript
TypeScript is an open-source object-oriented programming language developed and maintained by Microsoft Corporation. It is a strongly typed language and was first introduced in 2012. TypeScript is a strict superset of JavaScript, which means that anything implemented in JavaScript can be implemented
3 min read
TypeScript Object Type Index Signatures
In this article, we are going to learn about Object Type Index Signatures in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, index signatures allow you to define object types with dynamic keys, where the keys can be of a spe
2 min read
TypeScript Object
A TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data.What Are TypeScript Objects?An object
5 min read
Data types in TypeScript
In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity.Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Prim
3 min read
TypeScript Object Type Property Modifiers
TypeScript Type Property Modifiers are used to specify each property in an object such as: the type, whether the property is optional, and whether the property can be written to. TypeScript Object Type Property Modifiers:readonly Properties: An object type with readonly properties specifies that the
3 min read
TypeScript Object Intersection Types
In TypeScript, Object Intersection Types are a way to create new types by combining multiple types into a single type. This is done using the & (ampersand) operator. Intersection types allow you to express that an object must have all the properties and methods of each type in the intersection.
3 min read