[go: up one dir, main page]

DEV Community

Cover image for Tuples in TypeScript
Hayah Hazem
Hayah Hazem

Posted on

Tuples in TypeScript

What are Tuples?

Most of you know that TypeScript is type based. TypeScript offered a new datatype called "Tuple". This datatype is not in JavaScript. However it has some similarity with Arrays in JavaScript.

What differentiate Tuple from Array?

A few things :

  1. Tuples are more strict version of Array.
  2. You use it when you know the number of elements to be included.
  3. You know the position and type of each element.
  4. All elements should have different types to get full benefits of what the Tuple offers otherwise it won't be a Tuple anymore you could instead create an Array

How to declare Tuples in TypeScript?

  1. Common way :
const student : [string, number, string, string] = ['Sarah', 12, 'Math', 'Science'];
Enter fullscreen mode Exit fullscreen mode

Here the first element 'Sarah' is a string , second element 12
is number and so on.
If you tried to switch them up it will be compile time error:

Tuple type error in IDE

2- Second way :

type Student = [string, number, string, string];
Enter fullscreen mode Exit fullscreen mode

Tuples advanced features

  • We can store more than one value using the "Spread operator":
 type Student = [string, number, string, string];
 type Class = [string, ...Student[]];
 const floor : Class[] = [
    ["1A",
     ['Sarah', 12, 'Math', 'Science'],
     ['John', 12, 'Math', 'Science'], 
     ['Peter', 12, 'Math', 'Science']
    ],
    ["1B",
      ['Nadine', 12, 'English', 'Spanish'],
      ['Alex', 12, 'English', 'Spanish'],
      ['Julia', 12, 'English', 'Spanish']
    ]
  ]
Enter fullscreen mode Exit fullscreen mode

This is how the output will be:

Spread usage output

  • We can use them with "Rest parameters" in a function:
type Student = [string, number, string, string];
const createStudent = (...args : Student) => {};
createStudent('Sarah', 12 , 'Math', 'Science');
Enter fullscreen mode Exit fullscreen mode

while calling createStudent function your editor will notify you of the function expect as a parameter like the following :

function expected arguments

  • We can deconstruct them using the "Spread operators" and be able to use them in a regular functions:
const createStudent = (name : string, grade : number, subject1 : string, subject2 : string) => {}
type Student = [string, number, string, string];
const student1 : Student = ['Sarah', 12, 'Math', 'Science'];
createStudent(...student1);
Enter fullscreen mode Exit fullscreen mode

This is as if you did :

createStudent(student1[0], student1[1], student1[2], student1[3]);
Enter fullscreen mode Exit fullscreen mode

Conclusion

  1. Tuples are offered by Typescript to have more control on types and size unlike Arrays.
  2. Tuples are more strict than Arrays.
  3. It have fixed size and types and the types should be different.
  4. You can use it in functions or creating variables with rest parameters or spread operators

Small, basic tuples are very useful in their own right but when you delve a bit deeper and combine with generics, rest elements and others you can achieve some interesting results.

Top comments (3)

Collapse
 
gilfewster profile image
Gil Fewster

Good overview, but this line is not corrrect:

All elements must have different types otherwise it won't be a Tuple anymore

For example, this is a perfectly valid tuple

type Point2D = [number, number] 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hayah1999 profile image
Hayah Hazem

Yes, your line of code is correct. I guess my phrasing failed to get what I meant across.
What I meant is that yes all your tuple elements can be of the same type but you would lose one of the tuple benefits by doing that why didn't from the start create an array.
Thank you for your feedback I will edit my article so that confusion doesn't happen anymore

Collapse
 
gilfewster profile image
Gil Fewster

I see what you mean. It’s worth noting that you still get another benefit, even if all elements are the same type — a tuple must always have the correct number of elements, whereas the length of a JavaScript array can always be changed.