这些属性修饰符控制属性是否是必需的以及是否可以重新赋值。
可选(?)
ts
{
: ;
?: ;
}
: = { : };
: = { : , : };
() {
u..;
u.?.;
}
这些属性修饰符控制属性是否是必需的以及是否可以重新赋值。
?) {
: ;
?: ;
}
: = { : };
: = { : , : };
() {
u..;
u.?.;
}
可选属性的类型为 T | undefined,因此编译器会强制你处理缺失的情况——防止"cannot read property of undefined"的 bug。
interface Point { readonly x: number; readonly y: number; }
const p: Point = { x: 1, y: 2 };
p.x = 5; // ❌ Error: cannot assign to readonly property
// arrays too
const nums: readonly number[] = [1, 2, 3];
nums.push(4); // ❌ push doesn't exist on readonly array
readonly 只在编译时生效(无运行时强制),但它在类型系统中记录和强制不可变性,捕获意外修改。
interface Config { readonly id: string; tags?: readonly string[]; }
type Frozen = Readonly<User>; // utility type makes ALL props readonly
? 模型化真正的可选数据并强制空值安全;readonly 表达和强制不可变性(非常适合配置、props 和防止意外状态变更)。
两者都将正确性检查推入编译器。