Skip to the solution
EasyFrontend9 min read

What are tuple types?

629 views

The problem

Question presented to candidate: "What is a tuple type in TypeScript, how is it different from an ordinary array, and where have you used one?"

What a strong answer should cover:

  • A tuple fixes the length and the type at each position, such as [string, number]; its length is a literal type
  • How it differs from (string | number)[], and that an array literal is inferred as an array unless you annotate it or use as const
  • Optional elements ([number, number?]), rest elements ([string, ...string[]], also leading or middle since TypeScript 4.2) and labels ([x: number, y: number], TypeScript 4.0)
  • Tuples as rest parameters and variadic tuple types ([...T]) for typing argument lists
  • Everyday uses: returning a pair like useState, Object.entries style key/value pairs, coordinates
  • The pitfall: a mutable tuple still has push, so prefer readonly tuples for values you return

Code / implementation expected: Optional β€” declare a tuple, destructure it, and show one rejected out-of-range access.

  • tuple

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptTuple basics: positions, length and rejected access
TypeScriptOptional, rest, labelled and variadic tuples

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 8 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What is tsconfig.json and which options matter most?

Continue