【问题标题】:Passing self reference as parameter in abstract base class static function for use in child classes将自引用作为抽象基类静态函数中的参数传递给子类
【发布时间】:2020-06-01 16:41:03
【问题描述】:

在打字稿中,可以创建一个基类,该基类具有一个静态函数,子类可以使用该函数并返回调用子类的任何类型。此处显示TypeScript: self-referencing return type for static methods in inheriting classes

type Constructor<T> = { new (): T }

class BaseModel {
  static getAll<T>(this: Constructor<T>): T[] {
    return [] // dummy impl
  }

  /**
   * Example of static method with an argument:
   */
  static getById<T>(this: Constructor<T>, id: number): T {
    return // dummy impl
  }
}

class SubModel extends BaseModel {}
const savedSubs: SubModel = SubModel.getById(1234)

如何创建一个接受子类类型输入参数的函数呢?

在伪代码方面,它看起来像这样:

static getByChild<T>(this: Constructor<T>, child: this): T {
  return // dummy impl
}

但这不起作用。我怎样才能不可知地使方法参数成为这个基类的子类?

【问题讨论】:

  • 请注意,您需要 BaseModelSubModel 中的一些属性,以便它们是 structurally distinct from the empty type,否则您会发现像 SubModel.getByChild(1234) 这样的奇怪行为正在工作,因为 1234 extends {} 是真的。

标签: typescript inheritance static


【解决方案1】:

如果T 打算作为子类实例类型,如thisConstructor&lt;T&gt; 所证明的,那么您只需使用T 作为child 参数的类型:

static getByChild<T>(this: Constructor<T>, child: T): T {
  return child; // ?
}

您可以验证此方法是否有效:

const oneSub = SubModel.getById(123); // SubModel
const anotherSub = SubModel.getByChild(oneSub); // SubModel

希望有所帮助;祝你好运!

Playground link to code

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 2020-05-25
    • 2011-02-15
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多