gpt4 book ai didi

typescript - 使用 TypeScript 从基类中的静态方法实例化子类

转载 作者:搜寻专家 更新时间:2023-10-30 20:39:24 26 4
gpt4 key购买 nike

作为 TypeScript 的新手,在实例化子类类型的基类中实现静态工厂的最佳方法是什么。例如,考虑一个基本模型类中的 findAll 方法:

class BaseModel {
static data: {}[];
static findAll() {
return this.data.map((x) => new this(x));
}
constructor(readonly attributes) {
}
}

class Model extends BaseModel {
static data = [{id: 1}, {id: 2}];
constructor(attributes) {
super(attributes);
}
}

const a = Model.findAll(); // This is BaseModel[] not Model[]

这将返回 BaseModel[] 而不是 Model[]

最佳答案

为了回答我自己的问题,事实证明这是 TypeScript 中的一个众所周知的问题。 Github 问题 Polymorphic this for static methods进行了长时间的讨论。解决方案为follows :

export type StaticThis<T> = { new (): T };

export class Base {
static create<T extends Base>(this: StaticThis<T>) {
const that = new this();
return that;
}
baseMethod() { }
}

export class Derived extends Base {
derivedMethod() { }
}

// works
Base.create().baseMethod();
Derived.create().baseMethod();
// works too
Derived.create().derivedMethod();
// does not work (normal)
Base.create().derivedMethod();

关于typescript - 使用 TypeScript 从基类中的静态方法实例化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com