liveBook · Manning

Readonly type

As explained in Secrets of the JavaScript Ninja, Third Edition

A TypeScript type whose properties or elements cannot be modified through values of that type.

A TypeScript readonly type prevents mutation through values of that type, helping guard collections against unintended changes. It adds compile-time checks to ordinary JavaScript collections rather than replacing them. section 10.4.1 section 10.4.2

Readonly types apply to several collection forms:

  • Use `as const` for a readonly array literal; attempts to call `push` produce a TypeScript error. section 10.4.2
  • Use `ReadonlyMap` or `ReadonlySet` to prevent mutation through the typed collection. section 10.4.2
  • Readonly does not prevent reassignment: a variable can receive a new value if that value is also readonly. section 10.4.2
Listing 10.14 Creating read-only collections in TypeScript
const ninjas = ["Kuma", "Hattori", "Yagyu"] as const;  #A

ninjas.push("Waluigi"); // TypeScript error  #B

type NinjaName = (typeof ninjas)[number];  #C

interface NinjaMetadata {
  homeIsland: string;
}

const ninjaMetadata: ReadonlyMap<NinjaName, NinjaMetadata> =  #D
  new Map(  #D
    Object.entries({  #D
      Kuma: { homeIsland: "Honshu" },  #D
      Hattori: { homeIsland: "Hokkaido" },  #D
    }) as [NinjaName, NinjaMetadata][],  #D
  );  #D

ninjaMetadata.set("Yagyu", {  #E
  homeIsland: "Figi"  #E
}); // TypeScript error  #E

See readonly array and map declarations, plus examples of mutations that TypeScript rejects. section 10.4.2

Readonly types help prevent accidental mutation in your code. For complex state changes, Immer offers a separate approach: edit a draft and produce a modified copy. section 10.4.2 section 10.5

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Demonstrates compile-time checks for arrays, maps, and sets, and notes reassignment; does not describe runtime enforcement.
Examples
Uses a readonly array of ninja names and a ReadonlyMap of ninja metadata.
What you can do after
Apply TypeScript readonly types to collection values to catch attempted mutations at compile time.
How it connects
Connects readonly types with TypeScript, JavaScript collections, immutability, and Immer.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.