【发布时间】:2020-08-05 08:39:32
【问题描述】:
我正在尝试为我的 RESTful Web 服务创建一些实用程序类,以减少样板代码的数量。
这是我的实用程序类的简化示例:
class Model {
public static async findAll(options: any) {
return Promise.resolve([]);
}
}
class Service<M> {
public model: M;
// this will fix the following problem with "findAll". But we can't access "User" model members in "UsersService"
// public model: typeof Model;
constructor(options: { model: any }) {
this.model = options.model;
}
public async find(params?: any): Promise<any> {
return this.model.findAll(params); // error: Property 'findAll' does not exist on type 'M'
}
}
使用示例:
class User extends Model {
firstName: string;
lastName: string;
constructor(options: any) {
super();
this.firstName = options.firstName;
this.lastName = options.lastName;
}
}
class UsersService extends Service<typeof User> {
constructor() {
super({ model: User });
}
public async customMethod() {
const users = this.find({});
const newUser = new this.model({ firstName: 'foo', lastName: 'bar' });
newUser.firstName // ok
newUser.lastName // ok
}
}
我不知道应该如何为“Service”类定义类型参数,这样我才能访问“Service”类中的“findAll”,也可以访问“UsersService”中的“firstName”和“lastName”字段?
如果我将类型参数定义为“M extends Model”,那么我仍然无法访问静态成员。
【问题讨论】:
-
我能得到的最接近的是
class Service<M extends typeof Model> {,这使得一切正常,除了我得到一个Type 'typeof User' does not satisfy the constraint 'typeof Model'.,这对我来说没有多大意义。 -
我不确定,但构造函数通常不是类“类型”的一部分。定义一个定义
new()函数的接口可能会有所帮助,因此实现该接口的所有内容都必须以兼容的方式实现构造函数签名。 -
@Evert 实际上“模型”是一个库函数,因此复制这些声明可能会有点混乱
标签: typescript typescript-generics