What Is Tuple Type in TypeScript?

By Hemanta Sundaray on 2023-04-06

We know that JavaScript arrays can contain elements of different types. For example, an array can contain two elements — one of type string and the other of type number.

In TypeScript, when we define arrays with a fixed sequence of types, they are called tuples. What does “fixed sequence of types” mean? This means that the array must contain elements of specific types in a specific order.

In other words, tuples are a type of array that have a fixed length and each element has a specific type.

Consider the following example:

let myTuple: [string, number, boolean]
myTuple = ["hello", 42, true] // Valid
myTuple = [42, "hello", true] // Error: Type 'number' is not assignable to type 'string'

In the above example, myTuple is defined as a tuple type with a fixed sequence of types: string, number, and boolean, in that order. When we assign an array of elements that conform to this specific sequence of types, like ['hello', 42, true], it is considered valid. However, if we try to assign an array with elements in a different order, like [42, 'hello', true], TypeScript would raise a type error, indicating that the assigned value does not conform to the fixed sequence of types specified by the tuple type.

It's important to note that tuples in TypeScript are of fixed length, which means that the number of elements in a tuple is predetermined by its type definition. You cannot add or remove elements from a tuple without changing its type definition.

Join the Newsletter