This content originally appeared on DEV Community and was authored by Hayah Hazem
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 :
- Tuples are more strict version of Array.
- You use it when you know the number of elements to be included.
- You know the position and type of each element.
- All elements must have different types otherwise it won't be a Tuple anymore
How to declare Tuples in TypeScript?
- Common way :
const student : [string, number, string, string] = ['Sarah', 12, 'Math', 'Science'];
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:
2- Second way :
type Student = [string, number, string, string];
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']
]
]
This is how the output will be:
- 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');
while calling createStudent
function your editor will notify you of the function expect as a parameter like the following :
- 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);
This is as if you did :
createStudent(student1[0], student1[1], student1[2], student1[3]);
Conclusion
- Tuples are offered by Typescript to have more control on types and size unlike Arrays.
- Tuples are more strict than Arrays.
- It have fixed size and types and the types must be different.
- 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.
This content originally appeared on DEV Community and was authored by Hayah Hazem

Hayah Hazem | Sciencx (2023-03-26T21:54:18+00:00) Tuples in TypeScript. Retrieved from https://www.scien.cx/2023/03/26/tuples-in-typescript-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.