Dart、Kotlin 和 Swift 有一个惰性初始化关键字,主要出于可维护性的原因,可以让您避免使用可选类型。
// Using null safety:
class Coffee {
late String _temperature;
void heat() { _temperature = 'hot'; }
void chill() { _temperature = 'iced'; }
String serve() => _temperature + ' coffee';
}
TypeScript 有什么等价物?
最接近的是明确赋值断言。这告诉打字稿“我知道看起来我没有初始化它,但相信我,我做到了”。
class Coffee {
private _temperature!: string; // Note the !
heat() { this._temperature = "hot"; }
chill() { this._temperature = "iced"; }
serve() {
return this._temperature + ' coffee';
}
}
请注意,当您使用类型断言时,您是在告诉打字稿不要检查您的工作。如果您断言它已定义,但您忘记实际调用定义它的代码,则打字稿不会在编译时告诉您这一点,您可能会在运行时收到错误。
非常简单的选项:
function getImageUrl() {
let imageUrl;
// make your thing
imageUrl = "url(/img/sunny-landscape.png)";
return imageUrl;
}