Readonly and Record
Concept and syntax
Readonly<T> prevents assignment to mapped top-level properties through that typed view. Record<K,V> creates a property contract for each key in K with the same value type. Neither freezes nor constructs an object at runtime.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Rates=Readonly<Record<"small"|"large",number>>;const r:Rates={small:2,large:4}; console.log(r.small+r.large);Expected output:
6Common mistake
Intentionally invalid; compile separately and do not execute.
type Rates=Readonly<Record<"small"|"large",number>>;const r:Rates={small:2,large:4}; r.small=5;Expected diagnostic: TS2540. Readonly prohibits assignment through this view.
Practice and recap
Add a medium key and test the missing-key error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Readonly and Record — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Readonly and Record is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Rates=Readonly<Record<"small"|"large",number>>;const r:Rates={small:2,large:4}; console.log(r.small+r.large);Which diagnostic and explanation match the rejected example under the lesson settings?
type Rates=Readonly<Record<"small"|"large",number>>;const r:Rates={small:2,large:4}; r.small=5;What does Record<"a" | "b", number> require?