← 中文资源

简体中文版本

readonly 类型与不可变契约

用 readonly/ReadonlyArray/as const 把不可变性上提到类型层:变异 bug 变成编译错误,字面量级冻结连嵌套都封死。

阅读英文原文

运行结果

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

eu 2 3

实现说明

CONFIG 定义在模块顶层,中间不经过函数作用域。 模块级对象字面量,键名固定:x、y。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 跨调用保留的状态放在这些顶层绑定里:CONFIG。

核心语句

const route: Path = [ORIGIN, { x: 3, y: 4 }];
const ORIGIN: Point = { x: 0, y: 0 };
const ep: Endpoint = 'eu';

代码示例

interface Point {
  readonly x: number;
  readonly y: number;
}

type Path = readonly Point[];

const ORIGIN: Point = { x: 0, y: 0 };
const route: Path = [ORIGIN, { x: 3, y: 4 }];

// route[0].x = 9;        // readonly:编译错误
// route.push(ORIGIN);    // readonly array:编译错误

// as const:字面量级冻结(含嵌套)
const CONFIG = {
  retries: 3,
  endpoints: ['eu', 'na'],
} as const;
// CONFIG.retries = 5;             // 编译错误
// CONFIG.endpoints.push('apac');  // 编译错误

type Endpoint = (typeof CONFIG)['endpoints'][number];
const ep: Endpoint = 'eu';
console.log(ep, route.length, CONFIG.retries);