如何设置关联函数以使用 TypeScript 对模型进行续集(在 "sequelize.define" 之后)?

How do I set associate function to sequelize models with TypeScript (after "sequelize.define")?

要使用 sequelize 定义模型,您可以执行类似...

const User = sequelizeInstance.define<UserInstance>(
  'users',
  { /* fields */ },
  { paranoid: true } // and other options, like scopes
);

问题是我不知道如何使用 TypeScript 为模型定义 class 方法。似乎 sequelize 4 (?) 允许开发人员将 classMethods 属性 作为选项,但我使用的是 sequelize v6@types/sequelize v4.

export interface UserInstance extends Model<UserAttributes, UserCreationAttributes>, UserAttributes {
  getRoles: BelongsToManyGetAssociationsMixin<RoleInstance>;
  setRoles: BelongsToManySetAssociationsMixin<RoleInstance, number>;
}

const User = sequelizeInstance.define<UserInstance>(
  'users',
  { /* fields */ },
  { classMethods: { /* methods */} } // <= This is apparently deprecated
);

User.associate = (models) => { // TypeScript complains that associate doesn't exist
  User.belongsToMany(models.Role, { /* info about the pivot table*/ });
};

此选项似乎已被弃用。因此,TypeScript 警告 Property 'associate' does not exist on type 'ModelCtor<ModelInstance>'.ts(2339)

是否有任何替代方法来定义 class 方法(或者,仅定义 associate 函数)?我正在搜索 the doc,但找不到任何信息。

如有任何建议,我们将不胜感激。

PS: 我正在使用 TypeScript 4.1.3

您可以尝试这样的操作:

type UserStatic = typeof Model
    & { associate: (models: any) => void }
    & { new(values?: Record<string, unknown>, options?: BuildOptions): UserInstance }

const User = <UserStatic>database.define('users', {
...