kvn
kvn

Reputation: 1333

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.

Upvotes: 8

Views: 9222

Answers (1)

Art
Art

Reputation: 5924

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.

Upvotes: 3

Related Questions