Readonly
一句话解释
readonly modifier prevents assignment 到属性 or mutation 的数组, enforcing immutability at 类型 level.
用大白话说
readonly modifier marks a property or array as immutable. TypeScript will error if you try to assign a new value to a readonly property or call mutating methods on a readonly array.
For properties: 接口 点 { readonly x: 数字; } means x cannot be reassigned after creation. For arrays: readonly 数字[] removes push, pop, sort, and other mutating methods.
The Readonly<T> utility type makes all properties readonly at once. Note that readonly is shallow — nested objects can still be mutated. For deep immutability, you need a recursive type.
示例
typescript
interface Point { readonly x: number; readonly y: number; }
const p: Point = { x: 10, y: 20 };
// p.x = 30; // Error: cannot assign to readonly
const arr: readonly number[] = [1, 2, 3];
// arr.push(4); // Error: push does not exist on readonly arraysReadonly 属性 and 数组 cannot 是 mutated — TypeScript catches attempts at 编译时间.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。