TypeScript异步实例化 Posted on 2019-07-05 1234567891011121314151617181920212223242526class BaseClass { public constructor(protected element: HTMLElement) {} public static async build<T extends { new (...args: any[]): {} } = typeof BaseClass>( this: T, ...args: ConstructorParameters<T> ): Promise<InstanceType<T>> { const instance = new (this as any)(...args); await instance.init(); return instance; } protected async init(): Promise<void> {}}(async () => { // example1 class Example1 extends BaseClass {} const ex1 = await Example1.build(document.body); // 只需要传递HTMLElement就够了 // example2 class Example2 extends BaseClass { public constructor(protected element: HTMLElement, private id: number) { super(element); } } const ex2 = await Example2.build(document.body, 0); // 必须传递两个参数,HTMLElement和number})();