iMasters.com - Knowledge for Developers.
Follow Us
Home Frontend TypeScript: Tuples
Frontend

TypeScript: Tuples

For those unfamiliar with Tuples, they represent a simple array-like data structure. The big difference between the two is that in arrays we work with only one data type and with tuples with different types. To make it clearer, see below the declaration of an array of number and a tuple of string, number and string.

let list: Array<number> = [1, 2, 3]; //Exemplo com Array
let list: [string, number, string]; //Exemplo com tuplas

We can also declare a variable with an initial value in TS:

let list = [1, 2, 3]; //Exemplo com Array
let list = ['Thiago Adriano', 34, 'tadriano.net@gmail.com'];

After this brief introduction, let’s go to two practical examples: one with adding a value to a tuple and another accessing that value.

Adding Values ​​to a Tuple

As with the Array, we use .push() to add a new record to a tuple.

let list: [string, number] = ['Bill Gates', 1]; list.push('Steve', 2); console.log(list); //resultado: [ 'Bill', 1, 'Steve Jobs', 2 ]

Accessing values ​​in a tuple

Now to access these values, we can search for them by their index:

let list: [string, number] = ['Bill Gates', 1]; console.log(list[0]); //Bill console.log(list[1]); //1

Another way to access these values ​​is using a loop like foreach:

let list: [string, number] = ['Bill Gates', 1];
list.push('Steve Jobs', 2);
list.forEach(element => {
   console.log(element);
});
//Result:
Bill Gates
1
Steve Jobs
2

Pretty simple!

The idea here was to be something fast, and that could present one more of the features that we can use from TypeScript. I hope you liked it, see you in the next personal article

Written by
Thiago Adriano

Microsoft (MVP), currently works as Software Architect for TV Bandeirantes. In recent years, he has focused on technologies created by Microsoft, but he has always been on the lookout for new technologies that are emerging on the market. In short, he is passionate about what he does, he has his profession as a hobby.

Leave a comment

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Related Articles

BackendFrontend

Best practices you can use when making your commits

See in this article some of the good practices that you can...

BackendFrontend

How can the developer benefit from low code technologies?

One of the biggest myths in the area of ​​application development is...