在TypeScript中,late | lazy | lateinit的等价物是什么?

在TypeScript中,late | lazy | lateinit的等价物是什么?,typescript,null,initialization,optional,lazy-initialization,Typescript,Null,Initialization,Optional,Lazy Initialization,Dart、Kotlin和Swift有一个惰性初始化关键字,可以让您避免主要出于可维护性原因而使用可选类型 // Using null safety: class Coffee { late String _temperature; void heat() { _temperature = 'hot'; } void chill() { _temperature = 'iced'; } String serve() => _temperature + ' coffee';

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

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

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

  String serve() => _temperature + ' coffee';
}
TypeScript有什么等价物?

最接近的是a。这告诉typescript“我知道看起来我并没有初始化它,但相信我,我已经初始化了”


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

谢谢,但我不理解您在这里的警告:“使用类型断言,您是在告诉typescript不要检查您的工作。如果您犯了错误,typescript不会告诉您。”如果我理解,这将给出“找不到未定义的长度propName”如果我调用_temperature.length?如果您访问_temperature.length,typescript不会给您任何编译时警告,因为您已经告诉它假设它是一个字符串。但是,如果这个断言是错误的(即,您的代码中有一个bug,并且没有真正确保在所有情况下都定义了它),那么您可能会在运行时得到一个异常
class Coffee {
  private _temperature!: string; // Note the !

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

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