Skip to the solution
MediumFrontend10 min read

What is ReadonlyArray and readonly tuple?

998 views

The problem

Question presented to candidate: "What are ReadonlyArray and readonly tuples in TypeScript? How do they behave when you pass them to functions, and do they actually stop the array from changing?"

What a strong answer should cover:

  • ReadonlyArray<T>, readonly T[] and Readonly<T[]> are the same type: an array view with no mutating methods (push, sort, splice), no index writes and a read-only length
  • readonly [A, B] combines a tuple's fixed positions with the same read-only rules; as const on an array literal produces one
  • Assignability is one-way: a mutable array can be passed where a readonly one is expected, but not the reverse ('readonly' and cannot be assigned to the mutable type)
  • API design: accept readonly T[] parameters so callers can pass both kinds, and constrain generics with readonly unknown[]
  • It is compile-time only: the run-time value is an ordinary array, a mutable alias can still change it, and Object.freeze is the run-time counterpart
  • Version facts: the readonly T[] syntax, readonly tuples and as const arrived in TypeScript 3.4

Code / implementation expected: Optional β€” a function taking readonly number[], plus one rejected push or index assignment.

  • readonly-array

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptreadonly T[]: what is blocked and how it flows into functions
TypeScriptReadonly tuples, as const and generic constraints

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 22 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are type assertions and when should you use them?

Continue