常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。
核心语句
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);
}