namukang
namukang

Reputation: 294

How do I return the type of the subclass from the parent?

When calling a parent class' new this(), I'm having trouble figuring out how to return the type of the subclass, not the parent class.

In the example below, the code runs without errors, but child.hi() shows up as an error because child has type Parent and not Child.

class Parent {  
  static get() {
    return new this();
  }
}

class Child extends Parent {
  hi() {
    console.log('hi!');
  }

  static make() {
    const child = this.get();
    child.hi(); // <-- type error
  }
}

Child.make();

Typescript Playground Link

Upvotes: 0

Views: 73

Answers (1)

adamfsk
adamfsk

Reputation: 377

You can solve this by using a generic in the get method so that it will resolve the type correctly:

static get<T>(this: new () => T) {
    return new this();
}

After making this change, both Parent.get() and Child.get() should work as expected.

Upvotes: 3

Related Questions