constAPI=Object.freeze({BASE_URL:"https://api.example.com",VERSION:2,});API.VERSION=3;// silently fails (throws in strict mode)console.log(API.VERSION);// 2
Note freeze() prevents all changes. seal() allows modifying existing properties but not adding/removing. Both are shallow -- nested objects remain mutable.
// readonly is compile-time onlyconst arr:readonly number[]=[1,2,3];(arr as number[]).push(4);// No runtime protection
Example
interfaceConfig{readonly apiKey: string;readonly maxRetries: number;}const config:Config={ apiKey:"secret", maxRetries:3};// TypeScript prevents this:// config.apiKey = "changed"; // Error// But at runtime, nothing stops this:(config as any).apiKey="changed";// Works at runtime!console.log(config.apiKey);// "changed"// For real immutability, use Object.freeze:const safeConfig =Object.freeze({ apiKey:"secret", maxRetries:3});// safeConfig.apiKey = "x"; // Runtime TypeError + compile error
Output
// readonly is erased at runtime - use Object.freeze for true immutability
Note readonly, Readonly<T>, and ReadonlyArray are all compile-time only. They are stripped during compilation and provide zero runtime enforcement. Code that bypasses the type system (any casts, JavaScript interop) can still mutate. For sensitive data, combine readonly with Object.freeze or structuredClone.
Frequently asked questions
How does JavaScript handle Object.freeze?
This task is covered in 2 stacks on this page: JavaScript, TypeScript. The "Freezing and Sealing Objects" snippet in JavaScript uses `Object.freeze(obj)`.
Which code does the JavaScript example use?
The "Freezing and Sealing Objects" snippet uses `Object.freeze(obj)`, from the Objects section of the JavaScript cheat sheet.
Which stacks cover "Object.freeze" on this page?
JavaScript, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Freezing and Sealing Objects": freeze() prevents all changes. seal() allows modifying existing properties but not adding/removing. Both are shallow -- nested objects remain mutable.