我在为访问sequelize函数而编写的通用BaseService类定义类型时遇到问题。这是我班级的样子:
import { Model, Column } from 'sequelize-typescript'
import { BuildOptions } from 'sequelize'
type ModelStatic = typeof Model & {
new (values?: object, options?: BuildOptions): Model
}
abstract class EntityService<Entity = any> {
readonly entity
constructor(e) {
this.entity = e
}
async findAll(q = undefined): Promise<Entity[]> {
return await this.entity.findAll(q)
}
}
class UserEntity extends Model<UserEntity> {
@Column
name: string
}
class UserService extends EntityService<UserEntity> {
constructor() {
super(UserEntity)
}
foo() {
const users = this.findAll()
//Use the users here
}
}
我需要为通用类型Entity
,属性entity
和参数q
定义类型。
上面的代码工作正常。
对于键入,我进行了Entity extends Model<any>
,然后将entity
的类型设置为entity : ModelStatic
;现在,我在输入this.entity.findAll()
时得到建议,但是随后出现以下错误。
Type 'Model<any, any>' is not assignable to type 'Entity'.
'Model<any, any>' is assignable to the constraint of type 'Entity', but 'Entity' could be instantiated with a different subtype of constraint 'Model<any, any>'.
我了解此错误的含义,但无法解决该问题。