Tuples In TypeScript Simply Explained

TypeScript

28/08/2021


Tuples are arrays of a fixed minimum size and a specific element type order. Its type annotation resembles an array with elements of types.

TYPESCRIPT
let personTuple: [string, number]
personTuple = 11 // Type 'string' is not assignable to type '[string, number]'.
personTuple = [28, 'Jack'] // Type error!
personTuple = ['Anna', 27]
personTuple = ['John', 35, 'Doe'] // Works as well! 😃

TypeScript throws an error whenever you assign an insufficiently sized array or the wrong type order. However, there is no size restriction beyond the required minimum as the last line demonstrates!

Adding elements

Whenever you add elements, you should be aware that array indexing is not permitted 🙅‍♀️ by the linter beyond the defined size.

TYPESCRIPT
personTuple[2] = 'Bob' // Type '"Bob"' is not assignable to type 'undefined'.
personTuple.push(1)
personTuple[3] // Tuple type '[string, number]' of length '2' has no element at index '3'.
console.log(personTuple) // ["John", 35, "Bob", 1]

Of course, the code will still work as it's all valid JavaScript.

Not arrays

While tuples are arrays in JavaScript, TypeScript considers them as 2 ✌️ separate entities. Consequently, assigning an array to a tuple will fail.

TYPESCRIPT
let personArray = ['Mark', 41]
personTuple = personArray // Type error!

Spread syntax

A common use case for tuples is spreading them as arguments to a function. This can be particularly useful for a large amount of parameters.

TYPESCRIPT
function printPerson(name: string, age: number) { console.log(name, age) }
printPerson(...personTuple) // "Mark", 41

WRITTEN BY

Code and stuff