Readonly tuples and spreading
Concept and syntax
A readonly [string, number] tuple permits positional reads but rejects writes through that reference. Spreading ...entry into an array literal makes a new shallow array. Without contextual typing the spread result often loses fixed positions; an explicit tuple annotation can preserve them. A const assertion on the new array literal can also retain readonly tuple information.
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: readonly [string, number] = ["tea", 4];const copy: [string, number] = [...entry];copy[1] = 8;console.log(entry[1], copy[1]);Expected output (one line per log):
4 8Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
const entry: readonly [string, number] = ["tea", 4];entry[1] = 8;Expected compiler diagnostic: TS2540. Readonly tuple elements cannot be assigned through entry. Use a new mutable tuple when editing is required.
Practice and recap
Spread a readonly tuple into a mutable typed copy and edit the copy. Compare both values and try changing the original.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Readonly tuples and spreading — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which action creates a shallow new array?
Why annotate the copy as [string, number]?
Which change allows editing a new copy while preserving the original readonly reference?
const entry: readonly [string, number] = ["tea", 4];entry[1] = 8;