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]; itslengthis a literal type - How it differs from
(string | number)[], and that an array literal is inferred as an array unless you annotate it or useas 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.entriesstyle key/value pairs, coordinates - The pitfall: a mutable tuple still has
push, so preferreadonlytuples for values you return
Code / implementation expected: Optional β declare a tuple, destructure it, and show one rejected out-of-range access.