为什么构造函数签名与以下摘录中的接口声明不匹配,我应该如何重新表达它?报告的错误是
' Class' Item'错误地实现了界面' ItemClass'。 输入'项目'为签名' new(范围?:范围|未定义)提供不匹配:项目'。'
此代码的重点是工厂支持在运行时通过来自类的序列化的字符串名称标识的子类。抽象AsyncCtor定义并初始化Ready属性。我可以直接在
中这样做export interface ItemClass {
Ready: Promise<any>;
new(Scope?: Scope): Item;
}
export abstract class AsyncCtor {
public Ready: Promise<any> = new Promise((resolve, reject) => resolve(undefined));
}
export abstract class Item extends AsyncCtor implements ItemClass {
static Type: Map<string, ItemClass> = new Map<string, ItemClass>();
static register(typeName: string, typeClass: ItemClass): void {
this.Type.set(typeName, typeClass);
}
public static new(raw: any): Item {
let graph = typeof raw === "string" ? JSON.parse(raw) : raw;
let typeClass = Item.Type.get(graph.Type) as ItemClass;
let item = new typeClass();
...
return item;
}
constructor(public Scope?: Scope) {
super();
}
}
如果我停止声明 Item实现ItemClass的事实,那么所有内容都会编译,并且Item.new(raw)方法工作正常,所以很明显它确实实现了ItemClass。
在有人提出建议之前,我已经尝试了
constructor(public Scope?: Scope | undefined) {
答案 0 :(得分:0)
您正在将静态类方法与实例方法混合使用。
它应该类似于:
type ItemClassConstructor = {
new (Scope?: Scope): Item;
create(raw: any): Item;
}
interface ItemClass {
Ready: Promise<any>;
}
abstract class Item extends AsyncCtor implements ItemClass {
static Type: Map<string, ItemClassConstructor> = new Map<string, ItemClassConstructor>();
static register(typeName: string, typeClass: ItemClassConstructor): void {
this.Type.set(typeName, typeClass);
}
public static create(raw: any): Item {
let graph = typeof raw === "string" ? JSON.parse(raw) : raw;
let typeClass = Item.Type.get(graph.Type);
let item = new typeClass();
return item;
}
constructor(public Scope?: Scope) {
super();
}
}