Open In App

Explain the Tuple Types in TypeScript

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 using TypeScript, along with the choice of adding enhanced features. Essentially, every existing JavaScript code is valid TypeScript code.

In this article, we will learn about the tuple data type in TypeScript.

Tuple in TypeScript

A tuple is a new data type introduced by TypeScript. Unlike arrays, tuples can hold values of different data types. This flexibility allows tuples to be more versatile in certain scenarios compared to traditional arrays.

var geek: [boolean, string] = [true, "Aayush"];

Creating Tuples

Tuples can be created with elements of various data types. For example, consider the following tuple with element types boolean and string:

var nice: [boolean, string, number] = [true, "Aayush", 1];

You can also create tuples with multiple data types:

var nice: [boolean, string, number] = [true, "Aayush", 1];

Accessing Tuple Elements

As a tuple is a form of an array, we can use indexing to access individual elements in a tuple, just the way I have done in the following code:

Example:

JavaScript
var geek: [boolean, string] = [true, "Aayush"];
console.log(geek[0]);
console.log(geek[1]);

Output:

true
"Aayush"

Add Elements into Tuple

The push() function allows you to add additional members to a tuple. Let us understand this by looking an example, in the following code we are pushing a string to the already created geek tuple.

Example:

JavaScript
var geek: [boolean, string] = [true, "Aayush"];
geek.push("hello");
console.log(geek)

Output:

[true, "Aayush", "hello"]

You might also be tempted to push something other than string or boolean into the tuple geek, however, this will lead to an error. For example, running the following code

var geek: [boolean, string] = [true, "Aayush"];
geek.push(20);
console.log(geek)

gives the following error:

Argument of type '20' is not assignable to parameter of type 'string | boolean'.

Remove Elements from Tuple

The pop() function can be used to remove the last element from the tuple:

Example:

JavaScript
var geek: [boolean, string] = [true, "Aayush"];
geek.pop();
console.log(geek)

Output:

[true] 

Note: As tuples are a form of an array, you can easily use array functions like concat, map, etc., on a tuple.



Next Article

Similar Reads