Q9: What are Tuple Types in TypeScript and how do Readonly Tuples work?

Difficulty:EasyTopic:Data Structures

A Tuple is a fixed-length array where every element index has an explicitly declared type.

Standard tuples permit mutable array operations like .push(), which can bypass tuple index checks. Wrapping tuples with readonly enforces strict immutability.

Tuple and Readonly Tuple
type ResponseState = [code: number, message: string];
const state: ResponseState = [200, "OK"];

type ImmutableState = readonly [number, string];
const fixed: ImmutableState = [404, "Not Found"];
// fixed.push("error"); // Error: Property 'push' does not exist on type 'readonly [number, string]'
💡 Readonly tuples block array mutation methods like push, pop, or index modification.
Key Takeaways
  • Tuples lock array element types to explicit index positions.
  • Use readonly on tuples to block accidental array mutations.