Instantiating child class from a static method in base class, using TypeScript

前端 未结 2 1560
情歌与酒
情歌与酒 2020-12-31 08:51

Being new to TypeScript, what is the best method to implement a static factory in a base class that instantiates the child class type. For instance, consider a findAl

2条回答
  •  死守一世寂寞
    2020-12-31 09:54

    To answer my own question, this turns out to be a well known issue in TypeScript. The Github issue Polymorphic this for static methods has a long discussion. The solution is as follows:

    export type StaticThis = { new (): T };
    
    export class Base {
        static create(this: StaticThis) {
            const that = new this();
            return that;
        }
        baseMethod() { }
    }
    
    export class Derived extends Base {
        derivedMethod() { }
    }
    
    // works
    Base.create().baseMethod();
    Derived.create().baseMethod();
    // works too
    Derived.create().derivedMethod();
    // does not work (normal)
    Base.create().derivedMethod();
    

提交回复
热议问题