微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

打字稿——从基类中的静态方法实例化子项,使用参数并引用其他静态方法

如何解决打字稿——从基类中的静态方法实例化子项,使用参数并引用其他静态方法

我正在尝试从基类中的静态方法实例化子类。我想正确键入我的基类,而不是使用 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');

这会导致两个不同的错误

  1. Property 'getName' does not exist on type 'new (...args: any[]) => T'.(在 find 方法中)
  2. 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?