【发布时间】:2021-11-24 03:52:51
【问题描述】:
我如何用 typescript 解决这个问题?
ex:当你有一个类注册时,你想创建一个所有注册类的实例?
export abstract class FooAbstract {
static registers: typeof FooAbstract[] = []; // a registers
static create<T extends FooAbstract>(constr: new ()=>T) {
return new constr();
}
}
export class A extends FooAbstract {
name:string;
}
FooAbstract.registers.push(A); // in my case i use decoration, but not matter !
// what should be the good way here ?
const test = FooAbstract.registers.map((cls)=> cls.create(cls))
Argument of type 'typeof FooAbstract' is not assignable to parameter of type 'new () => FooAbstract'.
Cannot assign an abstract constructor type to a non-abstract constructor type.ts(2345)
【问题讨论】:
-
为什么不创建生成器函数工厂而不是基于类型的工厂?努力是完全一样的,但没有痛苦。
-
我是 typescript 的新手,你有这方面的 doc 参考吗?
-
请不要编辑问题以包含您自己的答案 - 这会使读者感到困惑,并绕过允许其他用户标记哪些答案最有帮助的投票机制。如果您对自己的问题有答案,则应将其作为答案发布。
-
ho oki 对,有意义
标签: typescript oop abstract-class