Search code examples
javascripttypescriptnullable

How to write a full property that is nullable


Sorry if it is a duplicate question, I can't find it...
I want to write out a property, but still keep it nullable.

I want

public foo?: string;

to be (but nullable)

  private _foo: string;
  public get foo(): string {
    return this._foo;
  }
  public set foo(v: string) {
    // some logic with 'v'...
    this._foo = v;
  }

Where do I put my ? or is there another way?
I tried with Nullable<string> but it doesn't work either.


Solution

  • You can write

    private _foo: string|null;
    public get foo(): string|null {
      return this._foo;
    }
    public set foo(v: string|null) {
      this._foo = v;
    }