3

Is there a way to obtain proper type using approach described below. I have tried make makeInstance() generic but I haven't obtained Extended type. Code below.

class Base {
  name = 'foo';

  static makeInstance() {
    return new this();
  }
}
class Extended extends Base {
  age = 10;
}

let base = Base.makeInstance() // is Base
let extended = Extended.makeInstance(); //should be Extended 

console.log(base.name);//ok
console.log(extended.age); //output ok; age doesn't exists
console.log(extended.name);// ok
2

1 Answer 1

7

You can add a generic parameter to the static method to infer the class on which the method is invoked correctly :

class Base {
    name = 'foo';

    static makeInstance<T>(this: new () => T) {
        return new this();
    }
}
class Extended extends Base {
    age = 10;
}

let base = Base.makeInstance() // is Base
let extended = Extended.makeInstance(); //is Extended 

console.log(base.name);//ok
console.log(extended.age); //ok
console.log(extended.name);// ok
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.