Tuples in TypeScript

·

3 min read

What is a Tuples

Tuple is an array like structure where each element at every index represents some property of a record. But the difference is that every single element inside the array like structure will represent one particular property about some record.

Online array where we have collection of information, Tuple contains different properties to describe one single thing.

Inside a tuple we will mix and match different data types.

Tuple is like an object in JS

See the below example to see the similarity between object and tuple

{
    color : 'Brown',
    carbonated : true,
    sugar : 40
}

['Brown', true, 40] // tuple

Instead of curly brackets, we put the values inside the array and it became a Tuples.

There is loss of information of keys when we changed the object to Tuple. Our code in Tuples is not self labelling.

const drink = {
    color : 'Brown',
    carbonated : true,
    sugar : 40
}

const drinkTuple = ['Brown', true, 40]

There is a problem here in drinkTuple, we can swap the order of values 'Brown', 40 and true and TypeScript will not see any problem with it. We need to do something about it.

Handling the order of our example

To declare drinkTuple as tuple, we will not use the curly brackets, instead we will use the square brackets and specify the exact order of properties we are entering in array. 'We will enter the order of properties'.

Once we specify the order of data types in array, it will become tuple

This is how our code will look once we are done specifying the order of property


const drinkTuple : [string, boolean, number] = ['Brown', true, 40]

Creating a type for our Tuple

We can create a type alias for our Tuple so we don't have to repeat out the definition of the properties of our Tuple again and again whenever we use it in our code.

We will start by writing the keyword 'type' keyword and then will name the custom_type and then make it equal to an array containing the data types.

This is how we will do it

type custom_type = [string, boolean , number];

// using the custom_type 
const tuple_custom : custom_type = ['name', true, 44];

Here is an example for the above code


type Drink = [string, boolean, number];

const drinkTuple : Drink = ['Brown', true, 40];

Revision

These are the steps we need to do to declare our Tuple

  1. Declare a separate type.

  2. The custom type will be an array with only property types mentioned

  3. Declare a custom tuple

  4. Add a : in front of custom tuple and write the custom type

  5. Write the array and add the values in the array as per the custom type defined

Thank you for reading. Any feedback will be appreaciated