← 中文资源

简体中文版本

Object.freeze 支撑 Readonly 配置类型

Object.freeze 与 Readonly 类型标注配合:运行时写入抛 TypeError,编译期索引写直接报错,数组冻结后 push 与下标写都被拒。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

localhost 8080 true
a,b 2

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。

核心语句

const config: Config = Object.freeze({ host: 'localhost', port: '8080' });
const rows: readonly string[] = Object.freeze(['a', 'b']);
config.host = 'other';

代码示例

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);
}