Advertisement
Intermediate TypeScript, Readonly, const Assertions & Immutability

How do you combine Object.freeze() with TypeScript's readonly to get genuine runtime immutability that also satisfies the type system?

Short answer

TypeScript's Object.freeze() type definition already returns a `Readonly `-typed result, so calling it both enforces ACTUAL runtime immutability (attempting to mutate silently fails in non-strict mode, or throws in strict mode) AND correctly reflects that immutability in the…

Save TypeScript mock interview
Advertisement
AModel answer
TypeScript's Object.freeze() type definition already returns a `Readonly<T>`-typed result, so calling it both enforces ACTUAL runtime immutability (attempting to mutate silently fails in non-strict mode, or throws in strict mode) AND correctly reflects that immutability in the type system simultaneously.
const config = Object.freeze({ theme: 'dark', retries: 3 });
// config is typed as Readonly<{ theme: string; retries: number }>
// config.theme = 'light'; // Error at compile time AND fails/throws at runtime
Real-world example
Creating a genuinely immutable shared constant object (like application configuration) with both compile-time and runtime protection.
Likely follow-ups
  • Does Object.freeze() perform a deep freeze, or only a shallow one — and what does that mean for nested objects?
Related topics