Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to unwrap an optional/nullable value in TypeScript?

I'm used to Swifts' optional values and see that TypeScript has something similar. For things like lazy initialisation of properties, it would be nice to have a private property that is nullable and a public getter that will initialise the value when requested.

class Test {
   private _bar: object:null = null;
   get bar(): object {
       if (_bar === null) {
           _bar = { };
       }
       return _bar;
   }
}

I know I could use undefined for this and remove the nullable type info from the private member, but I'm wondering if there is a way to do this without having to carry that null forever with the property. I'm going from a place where I want to handle null values to a boundary where I'd no longer wish for force anyone to deal with nullable values.

like image 935
kvn Avatar asked Dec 18 '17 19:12

kvn


1 Answers

You can do this in TypeScript like so:

class Test {
  private _bar?: object;
  get bar(): object {
    if (this._bar === undefined) {
        this._bar = { };
    }
    return this._bar;
  }
}

Typically using undefined instead of null is more idiomatic in TypeScript.

like image 66
Art Avatar answered Sep 28 '22 08:09

Art