Search code examples
typescripttypescript-types

typescript inheritance using static method


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

Solution

  • 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