Tutorial

TypeScript Tuples

Published on August 12, 2019
author

Alfred M. Adjei

TypeScript Tuples

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometimes we like to store values in an array with specific types. Using the any type can of course solve this problem but it will also allow certain types we might not want. This where tuples come in.

Say we want to create a user array of a userName and a userId;

let user: any;
let userId = 1;
let userName = "Alf";

let randomBoolean = true;

user = [userId, userName]; // valid
user = [userId, randomBoolean]; // also valid

By setting our user to be of the any type, we can assign any type to it and this defeats our purpose of having a userId which is a number and a userName which is a string type. We can use a tuple to solve this.

let user: [number,string];
let userId = 1;
let userName = "Alf";
let randomBoolean = true;

user = [userId, userName]; // valid
user = [userId, randomBoolean]; // error: Type 'true' is not assignable to type 'string'

We define a tuple by putting our intended types into square brackets and comma-separated, in this case, a number and a string. Now if we pass-in a type that isn’t defined in the tuple, say a boolean, we get an error message that says:

Type ‘true’ is not assignable to type ‘string’.

This is because we defined our tuple to accept a string as it’s second input but we passed in a boolean.

Accessing elements in a tuple

To access an element in a tuple, we use it’s index just like in an array.

console.log(user[0])  // 1
console.log(user[1])  // Alf

Tuples become very useful when we want to create a dictionary or a key-value pair. Using our example from above, we can have an array of user names and their ids without mistakenly passing in a different type to create problems later.

let users: [number, string][] = [[1,"Alf"],[2,"Jane"],[3,"Nii"]];

When assigning values to a tuple, the first two values must match exactly the types defined in the tuple.

For example, in our example above, our first element has to be a number and the second, a string. If we interchange the values, we will get an error even though their types have been defined in the tuple.

let user: [number,string];
user = ["Alf", 1]; // invalid

The above code is invalid because, user expects the first element to be a number and the second a string, but not vice-versa.

Any subsequent value we add to the tuple variable can be any of the predefined tuple types in no particular order.

user[2] = "John"; // valid
user[3] = 4; // valid
user[4] = true; // invalid. 

In the above code, because the tuple was declared with a number and a string, we can input an element of either the string or number in no order provided they aren’t the first two elements. We still can’t assign a boolean value to an element because the tuple wasn’t declared with a boolean type.

That’s it. Hope you found this post useful. ✨

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Alfred M. Adjei

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel