【发布时间】:2021-05-03 22:22:00
【问题描述】:
我正在尝试从基类中的静态方法实例化子类。我想正确键入我的基类,而不是使用 any 作为我所有静态方法的返回类型。我尝试了解决方案here,但它不适用于引用其他静态方法或接受参数的静态方法。如何正确地从 typescript 中的基类继承,并且仍然引用其他方法并接受参数?
class BaseClass {
id: string;
[key: string]: unknown;
static getName() {
return this.name.toUpperCase()
}
static async find<T extends BaseClass>(this: new (...args: any[]) => T, id: string)
: Promise<T> {
const tableName = this.getName();
const result: GetResult = db.find(tableName, id);
return new this(result);
}
}
class Child extends BaseClass {
name: string;
static findOne(id: string): Promise<Child> {
return this.find(id);
}
}
Child.find('abcd');
这会导致两个不同的错误
-
Property 'getName' does not exist on type 'new (...args: any[]) => T'.(在find方法中) -
Type 'BaseModel' is missing the following properties from type 'Child': name.(在findOne方法的返回类型中)
【问题讨论】:
标签: node.js typescript typescript-generics typescript-class