TypeScript 中的 strictPropertyInitialization
说明 strictPropertyInitialization 为什么会要求类属性在声明处或构造函数里被初始化,以及它如何减少未初始化实例状态的风险。
#tech / dev
#resource / typescript
#type / concept
#status / growing
[!info] related notes
TypeScript 中的 strictPropertyInitialization
一句话定义
strictPropertyInitialization 会要求类中声明的属性,要么在声明处初始化,要么在构造函数里保证赋值。
核心机制 / 工作原理
官方文档定义是:
- class property was declared but not set in the constructor
例如:
class UserAccount {
name: string;
accountType = "user";
email: string;
address: string | undefined;
constructor(name: string) {
this.name = name;
}
}
开启后,TypeScript 会指出:
email没有初始化,也没有在构造函数里被赋值
而像:
name已在构造函数里赋值accountType已有默认值address类型里允许undefined
这些都不会报错。
最小例子 / 最小场景
{
"compilerOptions": {
"strictPropertyInitialization": true
}
}
它最适合:
- 面向对象建模
- class-based framework 代码
- 对实例状态一致性要求较高的项目
边界与易混淆点
它和 strictNullChecks 有明显联动
如果一个属性的类型本身允许 undefined,那它就不必被强制初始化。
所以这两个选项的心智是连在一起的。
它不等于“每个字段都必须立刻有值”
如果某个字段本来就设计成可缺席,类型里应显式表达这一点。
它通常也跟着 strict 一起开
TSConfig 参考页当前把它列在 strict 相关项里。
参考信息
- TSConfig
strictPropertyInitialization: https://www.typescriptlang.org/tsconfig/strictPropertyInitialization.html - TSConfig Reference: https://www.typescriptlang.org/tsconfig/