TypeScriptBasic types

Tuples

Fixed-length arrays where each position has its own type.

On this page

Example

#
TypeScript
function minMax(values: number[]): [number, number] {
  return [Math.min(...values), Math.max(...values)]
}

const [lowest, highest] = minMax([72, 95, 64, 88])
console.log(lowest, highest)
Result
64 95

Definition and usage

#

A tuple is an array with a fixed number of elements and a known type at each position. The notation [string, number] means: the first element is a string, the second a number, and nothing else.

Tuples are great for returning a few values from a function, for example a pair of coordinates, or the result of useState in React, which returns [value, function].

You can name the positions for readability ([name: string, points: number]) and mark one as optional with a question mark. The names don’t change how it behaves, but they show up in the editor’s suggestions.

Syntax

#
Syntax
let pair: [string, number] = ["Emma", 120]

More examples

#
Named positions and a length error
TypeScript
type Score = [name: string, points: number]

const emma: Score = ['Emma', 120]
const wrong: Score = ['Jack', 90, true]
// Error: Source has 3 element(s) but target allows only 2.

Good practices

#
  • When a tuple has more than 2-3 positions, it’s better to return an object with named fields.
  • Destructuring with const [a, b] = ... is the most convenient way to read a tuple.

Related entries

#

Spotted a mistake or missing an example? Write to us.