Readonly Types For Immutable Contracts

Freeze data shapes at the type level with readonly, ReadonlyArray, and as const so mutation bugs become compile errors.

TypescriptData Integrity

Code

typescriptsnippet
24 lines
interface Point {
  readonly x: number;
  readonly y: number;
}

type Path = readonly Point[];

const ORIGIN: Point = { x: 0, y: 0 };
const route: Path = [ORIGIN, { x: 3, y: 4 }];

// route[0].x = 9;        // readonly:编译错误
// route.push(ORIGIN);    // readonly array:编译错误

// as const:字面量级冻结(含嵌套)
const CONFIG = {
  retries: 3,
  endpoints: ['eu', 'na'],
} as const;
// CONFIG.retries = 5;             // 编译错误
// CONFIG.endpoints.push('apac');  // 编译错误

type Endpoint = (typeof CONFIG)['endpoints'][number];
const ep: Endpoint = 'eu';
console.log(ep, route.length, CONFIG.retries);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

eu 2 3

How this snippet works

Top-level bindings CONFIG hold the demo state — nothing sits inside a function scope.

The top-level object literal pins x, y as plain values — no derivation, no imports behind them.

Statements that matter

const route: Path = [ORIGIN, { x: 3, y: 4 }];
const ORIGIN: Point = { x: 0, y: 0 };
const ep: Endpoint = 'eu';

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `CONFIG`.