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

1

8

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.

Vickievicksburg answered 18/12, 2017 at 19:43 Comment(0)
C
3

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.

Cubature answered 18/12, 2017 at 19:51 Comment(5)
Yeah this is what I've done myself for now, but I was thinking there might still be cases where null is more appropriate or a valid value and you want to move it into a value that is no longer nullable at some point.Vickievicksburg
Not sure what you mean, can you give an example? - if you want to use null instead of undefined you can do that as well. If you don't want to mark the value as optional then you'll need to give it some value.Cubature
So in Swift, if a value is optional, But I want to unwrap it so that I know that from now on it's no longer optional I can just do if let nonOptVal = optVal { } or I can use a guard let nonOptVal = optVal else { throw err } and then the data is stored in the non-optional variable nonOptVal and I can use it assuming the value exists. I was wondering if there is an equivalent in Typescript. So far the only workaround I have is to cast the type to one that doesn't include |undefined or |null.Vickievicksburg
@Kevin this is what I've been doing: if ((value = this.optionalValue) != undefined) { console.log(value+" is valid") }Isolating
I'll add a C# equivalent here if( optVal is string nonOptVal ){ ... }, which does the equivalent of Swift's let statement. Any equivalent in Typescript?Brandenburg

© 2022 - 2024 — McMap. All rights reserved.