TypeScript静态方法继承

同步版本

class Foo {
    static boo<T extends typeof Foo>(this: T, a: number): InstanceType<T> {
        return (new this()) as InstanceType<T>;
    }
}

class Bar extends Foo {}

// b: Bar
let b = Bar.boo(1);

异步版本

class Foo {
    static async boo<T extends typeof Foo>(this: T, a: number): Promise<InstanceType<T>> {
        const instance = new this();
        await instance.create();
        return <InstanceType<T>>instance;
    }
    private create(){}
}

class Bar extends Foo {}

(async () => {
    // b: Bar
    let b = await Bar.boo(1);
})();

引用自:https://github.com/Microsoft/TypeScript/issues/5863

原文地址:https://www.cnblogs.com/ystrdy/p/9597508.html