6

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 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I am using Sequelize with Feathers.js, so I need to use the sequelize.define(... approach. The example given here: docs.sequelizejs.com/manual/typescript, shows your method and works well (I assume), when you are working directly with classes.
@Aston Could you give the sequelizeInstance contents?
@Laiso It is basically new Sequelize(url, config) but here is my complete file I use gist.github.com/eshton/03ec6cf7b14b8e74843ccea7c5ff4815

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.