首页 > 解决方案 > 什么相当于迟到 | 懒惰 | 打字稿中的后期初始化?

问题描述

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 有什么等价物?

标签: typescriptnullinitializationoptionallazy-initialization

解决方案


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

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

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

  serve() { 
    return this._temperature + ' coffee';
  }
}

请注意,当您使用类型断言时,您是在告诉 typescript 不要检查您的工作。如果你犯了错误,打字稿不会告诉你。


推荐阅读