Object.freeze Backs Readonly Config Types
Object.freeze pairs with Readonly type annotations so runtime writes throw TypeError while compile-time index writes fail before the build.
Code
type Config = Readonly<Record<string, string>>;
const config: Config = Object.freeze({ host: 'localhost', port: '8080' });
console.log(config.host, config.port, Object.isFrozen(config));
// freeze 对数组同样生效:readonly 数组运行时拒绝 push 与写
const rows: readonly string[] = Object.freeze(['a', 'b']);
console.log(rows.join(','), rows.length);
try {
// @ts-expect-error readonly 索引写在编译期就被拦下
config.host = 'other';
} catch (error) {
console.log('write blocked:', error instanceof TypeError);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
localhost 8080 true
a,b 2How the run progresses
Object.freeze returns a deeply shallow guarantee at runtime — top-level property
assignment on config throws TypeError (the try/catch prints write blocked: true),
and Object.isFrozen(config) reports true right after freezing. Nested objects would
still stay mutable, so the Readonly<Record<string, string>> annotation is what closes
the gap at compile time: assigning to config.host fails type-check before the build
(the @ts-expect-error comment documents that), while arrays wrapped in readonly string[]
reject push and index writes once frozen — rows.join(',') prints a,b with length 2.
Statements that matter
const config: Config = Object.freeze({ host: 'localhost', port: '8080' });
const rows: readonly string[] = Object.freeze(['a', 'b']);
config.host = 'other';
Interactive Tools for This Topic
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do.
Report a problem with this exampleOpens a pre-filled issue on GitHub.