How to define properties that can be used on a class before constructing (eg. for a factory method)?

Viewed 59

Example code:

class User {
  name: String;
  constructor(name: String) {
    this.name = name;
  }
}

User.get = (name):User => {
  return new User(name);
}

Use:

// Should return User bob
var user = User.get("bob")

// Should also return User bob
var user = new User("bob")

Error:

Property 'get' does not exist on type 'typeof User'.ts(2339)

I want to know how to define this property so that I don't get this error. Also, yes I know I can just define the get function inside the class User, but for other reasons, I want to be able to call the get function on the class itself.

1 Answers

Declare get (or maybe create) as a static function of User:

class User {

  static get(name: string): User {
    return new User(name);
  }

  name: string;

  constructor(name: string) {
    this.name = name;
  }
}

Now, const user = User.get("bob"); should work. I hope this suits your last paragraph of your question well.

Related