我有 Python 背景,在尝试使 Typescript 对以下继承模型满意时遇到了一些问题。
给定以下基类:
// model.ts
export class Model {
serialize() {}
static deserialize(dbRow) {}
static async filter(options) {
const dbRows = await getData(options);
return dbRows.map(row => this.deserialize(row));
}
}
以及扩展它的以下类:
// user.ts
export class User extends Model {
serialize() {......}
static deserialize(dbRow) {......return new User(......)}
someOtherMethod() {.....}
}
我如何定义 Model.filter 以便 const users = await User.filter({.....})
会自动将用户类型推断为 User[]?现在,推断的类型是 Model[]。
我知道我能做到const users = <User[]> await User.filter({....})
但我想知道是否有任何方法建议将 Model.filter 的返回类型作为类构造函数,以便正确推断子类的实例。
最佳答案
您可以使用以下解决方法(在 this thread 中多次提及):
type ModelContructor<T> = new () => T;
class Model {
// ...
static async filter<T extends Model>(this: ModelContructor<T> & typeof Model, options): Promise<T[]> {
const dbRows = await getData(options);
return dbRows.map(row => this.deserialize(row));
}
}
这里我们使用伪造的this
参数,它强制T
在User.filter
时被解析为User
打电话。
关于class - 基类中工厂方法的 typescript 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48380983/