skip to Main Content

My problem is similar to this:

Type Name = {firstName: string, lastName: string}

class NameClass {
  public _name: Name | null;

  constructor() {
    this._name = null;
  }

  // or any function
  public set name(name: Name) {
    this._name = name;
  }

  public printName() {
    if (!this._name) this.name = { firstName: "should not", lastName: "be null" };
    //          v Object may be null even though I just set it ^
    console.log(this._name.firstName);
  }
}

I’m aware I can simply use the " ! " assertion to get around this or can create a separate function to make sure that the object is not null, but I’m looking for a way to tell typescript that the function will set the property.

There is a solution proposed in question

but I find this kind of hacky and doesn’t really solve the problem. The post was also 4 years ago, so I’m hoping there is a better way to fix this?

2

Answers


  1. If im not mistaken, the problem is not telling typescript "how to do it" – it is simply not possible. The class cannot and will never know, what nullable property was set in what function (or some other way). The whole point of having a nullable property is to have the opportunity to set that property to null. Even after setting the property, it may return back to null (e. g. through another function).

    A work around would be having that property set to defalt string values ("") in the constructor.

    Also as a side-note, it is not recommendet to have a public property start with an underscore. Normally, only private fields are named like that.

    Login or Signup to reply.
  2. Have you considered initializing the _name property in the constructor?

    type Name = {firstName: string, lastName: string}
    
    class NameClass {
      public _name: Name;
    
      constructor() {
        this._name = { firstName: "should not", lastName: "be null" };
      }
    
      // or any function
      public set name(name: Name) {
        this._name = name;
      }
    
      public printName() {
        console.log(this._name.firstName);
      }
    }
    

    Typescript is okay with that, because that way _name is always set.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search