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
