TYPESCRIPT / CHAPTER 04

Tuples, rest parameters, and array boundaries

Intermediate

Use positional contracts when each position has a different meaning.

By the end of this chapter

  • Distinguish tuples from general arrays
  • Handle optional tuple elements
  • Preserve readonly input contracts

The idea

A tuple describes a fixed arrangement of positions, such as a label followed by a count. A general array describes repeated elements but does not establish that a particular position exists. Tuple labels improve readability without changing runtime behavior. Rest parameters can use a tuple to connect each argument position to its intended type.

An optional tuple element can be absent, so reading it includes undefined under strict checking. A readonly tuple restricts writes through that view but still represents an ordinary JavaScript array at runtime. For general array indexing, enabling noUncheckedIndexedAccess adds undefined to reads that may be out of bounds. Regardless of compiler options, runtime algorithms must still check lengths or handle absent values.

TypeScript example
function line(...[name, count = 1]: [name: string, count?: number]): string {
  return name + ":" + count;
}
console.log(line("item"));
console.log(line("item", 0));
Result
item:1
item:0

The optional count defaults only when undefined, preserving zero.

Try it yourself

Accept a readonly coordinate pair and return a translated pair without changing the original.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which type represents exactly a string first and a number second?