Search code examples
typescriptnullinitializationoption-typelazy-initialization

What is the equivalent of late | lazy | lateinit in TypeScript?


Dart, Kotlin and Swift have a lazy initialization keyword that lets you avoid the usage of Optional type mainly for maintainability reason.

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

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

  String serve() => _temperature + ' coffee';
}

What does TypeScript has as equivalent ?


Solution

  • The closest is a definite-assignment assertion. This tells typescript "i know it looks like i didn't initialize this, but trust me, i did".

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

    Be aware that when you use type assertions, you are telling typescript not to check your work. If you assert that it's defined, but you forget to actually call the code that makes it be defined, typescript will not tell you about this at compile time and you may get an error at run time.