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
Leave a comment