如何解决打字稿——从基类中的静态方法实例化子项,使用参数并引用其他静态方法
我正在尝试从基类中的静态方法实例化子类。我想正确键入我的基类,而不是使用 any
作为所有静态方法的返回类型。我尝试了解决方案 here,但它不适用于引用其他静态方法或接受参数的静态方法。如何正确继承打字稿中的基类,并且仍然引用其他方法并接受参数?
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
方法的返回类型中)
解决方法
在基类的 find
方法中,您应该指定它期望子类实现静态 getName
方法,如下所示:
static async find<T>(this: { new (arg: GetResult): T } & typeof BaseClass,id: string): Promise<T>
特别是 { new (arg: GetResult): T }
为您带来构造函数,而 typeof BaseClass
为您带来静态成员。
我嘲笑了一些缺失的部分并进行了类型检查。
type GetResult = string;
const db = {
find: (a: string,b: string) => "bar",}
class BaseClass {
id: string = "bzzzz";
[key: string]: unknown;
static getName() {
return 'NAME'
}
static async find<T>(this: { new (arg: GetResult): T } & typeof BaseClass,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 = "Child";
static findOne(id: string): Promise<Child> {
return this.find(id);
}
}
Child.find('abcd');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。