原文链接: ts 使用 prototype 实现单例模式并支持推断
上一篇: angle-normals-ts 求三角形法线 画小刺兔
下一篇: 冯氏光照模型(Phong Lighting Model) 简单实现
如果不使用prototype 推断的是Super, 这样就比较难以复用了
class Base {
async init() {}
static async getInstance<T extends typeof Base>(
this: T
): Promise<T["prototype"]> {
const base = new this();
await base.init();
return base;
}
}
class Super extends Base {
async init() {
await fetch("Super");
}
}
async function main() {
const base: Base = await Super.getInstance();
}