【问题标题】:What is the equivalent of late | lazy | lateinit in TypeScript?什么相当于迟到 |懒惰 |打字稿中的后期初始化?
【发布时间】:2021-06-24 19:45:12
【问题描述】:

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

【问题讨论】:

    标签: typescript null initialization optional lazy-initialization


    【解决方案1】:

    最接近的是definite-assignment assertion。这告诉打字稿“我知道它看起来像我没有初始化它,但相信我,我做到了”。

    class Coffee {
      private _temperature!: string; // Note the !
    
      heat() { this._temperature = "hot"; }
      chill() { this._temperature = "iced"; }
    
      serve() { 
        return this._temperature + ' coffee';
      }
    }
    

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

    【讨论】:

    • 谢谢,但我不明白你在这里的警告:“使用类型断言,你是在告诉 typescript 不要检查你的工作。如果你犯了错误,typescript 不会告诉你的。”如果我理解,如果我调用 _temperature.length,这将给出“找不到长度 propName of undefined”?
    • 如果你访问 _temperature.length,typescript 不会给你任何编译时警告,因为你告诉它假设它是一个字符串。但是,如果该断言是错误的(即,您的代码中有错误,并且实际上并没有确保它在所有情况下都已定义),那么您可能会在运行时遇到异常
    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 2022-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2017-03-11
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多