Working with TypeScript Tuples - A Step-by-Step Guide

24 Jun 2023 Balmiki Mandal 0 Typescript

Working with TypeScript Tuples

TypeScript tuples are an excellent way to store data of different shapes and sizes in an array-like structure. They are similar to arrays, except for one key difference – the types of elements they store must be known ahead of time and can not be changed once placed inside the tuple. Tuples are useful for storing related information that’s not necessarily the same type, such as a person’s name and age, or a city’s longitude and latitude.

Creating a Tuple

You can create a tuple by simply placing multiple elements in parentheses, separated by commas, like this:

let player: [string, number] = ["John Smith", 34];

This tuple contains two elements: a string representing the player’s name, and a number representing their age. It is important to note that the types of the elements in the tuple must be specified, so adding a line like this would cause an error:

let player: [string, number] = ["John Smith", false];  // Error

The second element in the tuple should always be a number!

Accessing Elements

You can access the individual elements of a tuple using array notation, like this:

console.log(player[0]);  // Prints “John Smith”
console.log(player[1]);  // Prints 34

You can also use the .length property to get the length of the tuple, just like an array.

Changing Elements

Unlike arrays, you cannot change the elements of a tuple once it has been created. If you need to change the type, you will first need to create a new tuple and then assign it to the original variable.

Conclusion

Tuples can be a great way to store related data that isn’t necessarily of the same type. They are easy to create and use, but you should be careful to make sure that the types of the elements remain consistent. With a little practice, you'll be working with TypeScript Tuples like a pro in no time!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.