TypeScript异步实例化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class 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
})();