问题描述
来自 Python 背景,我在尝试使 Typescript 对以下继承模型满意时遇到了一些问题.
Coming from a Python background, I encountered a few problems while trying to make Typescript happy with the following inheritance model.
给定以下基类:
// 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[].
How could I define Model.filter so that const users = await User.filter({.....})
will automatically infer the type of users as User[]? Right now, the inferred type is Model[].
我知道我可以做到 const users = await User.filter({....})
但我想知道是否有任何方法建议将 Model.filter 的返回类型作为类构造函数,以便正确推断子类的实例.>
I know I can do const users = <User[]> await User.filter({....})
but I wonder if there is any way of suggesting the return type of Model.filter as the class constructor so that instances of child classes will be inferred correctly.
推荐答案
您可以使用以下解决方法(在 这个线程):
You can use the following workaround (mentioned several times in 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
调用.
Here we use fake this
parameter, which enforces T
to be resolved as User
when User.filter
called.
这篇关于Typescript 返回基类中工厂方法的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!