迟到相当于什么?懒惰| TypeScript 中的 Lateinit ?

TSR*_*TSR 16 null initialization lazy-initialization typescript option-type

Dart、Kotlin 和 Swift 有一个延迟初始化关键字,主要出于可维护性的原因,可以让您避免使用可选类型。

// Using null safety:
class Coffee {
  late String _temperature;

  void heat() { _temperature = 'hot'; }
  void chill() { _temperature = 'iced'; }

  String serve() => _temperature + ' coffee';
}
Run Code Online (Sandbox Code Playgroud)

TypeScript 有什么等价物?

Nic*_*wer 32

最接近的是明确赋值断言。这告诉打字稿“我知道看起来我没有初始化它,但相信我,我做到了”。

class Coffee {
  private _temperature!: string; // Note the !

  heat() { this._temperature = "hot"; }
  chill() { this._temperature = "iced"; }

  serve() { 
    return this._temperature + ' coffee';
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,当您使用类型断言时,您是在告诉打字稿不要检查您的工作。如果您断言它已定义,但忘记实际调用定义它的代码,则打字稿不会在编译时告诉您这一点,并且您可能会在运行时收到错误。