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
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
To access an element in a tuple, we use it’s index just like in an array.
console.log(user) // 1 console.log(user) // 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 = "John"; // valid user = 4; // valid user = 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
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
That’s it. Hope you found this post useful. ✨
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.Sign up