1. 程式人生 > >TypeScript靜態方法繼承

TypeScript靜態方法繼承

uri code bar script foo sof () turn wait

同步版本

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

TypeScript靜態方法繼承