Using Sequelize.Instance with Sequelize v5 & Typescript

Viewed 4265

In most guides, chats, tutorial etc... the recommended way to type Sequelize models is to use the following code:

export interface IUserInstance extends Sequelize.Instance<IUserAttributes>, IUserAttributes {
  prototype: {
    verifyPassword: (password: string) => boolean;
  };
}

the key part here is Sequelize.Instance<, in Sequelize v5+ you see the error:

Namespace '".../node_modules/sequelize/types/index"' has no exported member 'Instance'.

I have looked around but have not come across solution.

** Looking at this guide, section "Usage of sequelize.define" http://docs.sequelizejs.com/manual/typescript

There does NOT seem to be a clear way of working with associations in using define and typescript.

Any help / advice would be appreciated.

References:

Regards, Emir

1 Answers

I searched a lot for a solution to this problem, and got it working with the following:

import sequelizeInstance from '..';
import { Model, DataTypes } from 'sequelize';

const config = {
  tableName: 'User',
  sequelize: sequelizeInstance,
};

class User extends Model {
  id!: number;
  firstName!: string;
  lastName!: string;
  /* some other properties*/

  verifyPassword: (password: string) => boolean;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}
User.init(
  {
    id: {
      primaryKey: true,
      type: DataTypes.INTEGER,
      autoIncrement: true,
    },
    firstName: {
      type: DataTypes.STRING,
    },
    lastName: {
      type: DataTypes.STRING,
    }
  },
  config,
);

User.prototype.verifyPassword = function(password: string) {
  /* code here ... */
};

export default User;
Related