同步版本

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

posted on 2018-09-06 11:48  ystrdy  阅读(591)  评论(0编辑  收藏  举报