Tuple inference and destructuring
Concept and syntax
An ordinary array literal with mixed values usually infers a union array, not a positional tuple. Annotate a tuple to preserve positional information. Destructuring const [label, count] = entry binds elements by position; the compiler uses the tuple type to infer each binding separately. A missing element in an ordinary array can still yield undefined at runtime.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const entry: [string, number] = ["tea", 4];const [label, count] = entry;console.log(label.toUpperCase(), count * 2);Expected output (one line per log):
TEA 8Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
const entry = ["tea", 4];const [label, count] = entry;const n: number = count;Expected compiler diagnostic: TS2322. An inferred union array does not promise that the second element is numeric. Annotate the intended tuple.
Practice and recap
Destructure a typed tuple into text and count. Remove its tuple annotation and compare the inferred type of count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tuple inference and destructuring — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
How does a tuple annotation help destructuring?
What is usually inferred for const entry = ["tea", 4]?
How can the declaration preserve the intended numeric second position?
const entry = ["tea", 4];const [label, count] = entry;const n: number = count;