问题描述
Dart、Kotlin 和 Swift 有一个惰性初始化关键字,可让您避免使用 Optional 类型,主要是出于可维护性的原因。
// Using null safety:
class Coffee {
late String _temperature;
void heat() { _temperature = 'hot'; }
void chill() { _temperature = 'iced'; }
String serve() => _temperature + ' coffee';
}
TypeScript 有什么等价物?
解决方法
最接近的是 definite-assignment assertion。这告诉打字稿“我知道看起来我没有初始化它,但相信我,我做到了”。
class Coffee {
private _temperature!: string; // Note the !
heat() { this._temperature = "hot"; }
chill() { this._temperature = "iced"; }
serve() {
return this._temperature + ' coffee';
}
}
请注意,当您使用类型断言时,您是在告诉打字稿不要检查您的工作。如果你犯了错误,打字稿不会告诉你。