October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Use Readonly Arrays in TypeScript

Use readonly T[] for inspection-only array references, ReadonlyArray as its generic equivalent, and readonly tuples for fixed positional types.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use readonly T[] to give code read access to an array without allowing writes through that reference. For example, readonly string[] and ReadonlyArray<string> describe the same kind of readonly array. Use readonly [A, B] when you need a fixed tuple with known types at each position.

Choose the array type that matches the contract

Type Use it when What it expresses
readonly T[] The sequence can vary in length and contains values of one element type. Code using this reference may inspect elements but cannot write to slots or call mutating array methods.
ReadonlyArray<T> You prefer the generic spelling. It is equivalent to readonly T[].
readonly [A, B] The sequence has a fixed shape and distinct types by position. Positions retain their individual types, but cannot be written through this reference.
T[] Mutation is part of the function or variable’s contract. Code with this type can use array writes and mutating methods.

TypeScript documents readonly arrays and tuples in its Object Types Handbook and TypeScript 3.4 release notes.

As an Amazon Associate I earn from qualifying purchases.

Declare and use a readonly array

Prefix the element type and brackets with readonly. Reading an element and calling non-mutating methods such as slice are allowed; assigning to an index or calling push is rejected during type checking.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function first(values: readonly string[]): string | undefined {
  const initial = values[0]; // allowed
  const copy = values.slice(); // allowed
  // values.push("x"); // type error
  // values[0] = "x"; // type error
  return initial;
}

const names: ReadonlyArray<string> = ["Ada", "Grace"];

The readonly restriction applies to operations performed through the typed reference. It does not prevent another mutable reference to the same array from changing it.

Use readonly parameters for inspection-only functions

If a function only needs to examine its input, accept readonly T[] (or ReadonlyArray<T>). A caller can pass a mutable array, but the function’s parameter type does not expose array mutation methods or indexed writes. This avoids requiring a mutable input when the function does not need one.

function total(values: readonly number[]): number {
  return values.reduce((sum, value) => sum + value, 0);
}

const scores = [8, 9, 10];
const result = total(scores); // allowed

If a function must change the supplied array, declare its parameter as T[] and make that mutation part of its API contract. TypeScript permits assigning a mutable array to a readonly array type, but not assigning a readonly array to a mutable array type: otherwise the receiving code could modify a value that its type promises is readonly.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Use readonly tuples for fixed positions

A readonly tuple keeps the types and positions of its elements while disallowing slot writes. This is useful for pairs or other fixed-shape values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function pointDistance(pair: readonly [number, number]): number {
  const [x, y] = pair; // reading and destructuring are allowed
  // pair[0] = 0; // type error
  return Math.sqrt(x * x + y * y);
}

Readonly array shorthand and readonly tuple support were introduced in TypeScript 3.4, as documented in the 3.4 release notes.

Know what readonly does—and does not—guarantee

readonly is a type-level restriction, not runtime freezing. It does not call Object.freeze, guarantee deep immutability, or stop other aliases from changing the underlying array. A readonly object property whose value is an object prevents replacing that property through the readonly reference; it does not by itself prevent changing fields inside the referenced object. The Handbook’s object types documentation explains these limits.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use the supported syntax

The modifier goes before an array or tuple literal type: write readonly boolean[] or readonly [string, number]. Do not write readonly Array<boolean> or readonly Set<number>; the modifier cannot prefix those generic type forms. For a generic array spelling, use ReadonlyArray<boolean>. These syntax rules are described in the TypeScript 3.4 release notes.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.