Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Type does sequelize.define() return in TypeScript?

So I finally decided to try out TypeScript, because of everything I've heard about it and how having static types is good for me. I decided to test it out by creating a simple web API with sequelize, but I am having trouble understanding the types returned from sequelize. So I have the following imports (note that I've also installed the @types/sequelize npm module:

import sequelize = require('sequelize');
import  {DataTypes} from 'sequelize';

I am creating my model like this:

    const User:sequelize.Model= db.define('User',{
        id: {type:DataTypes.INTEGER, primaryKey:true},
        email:{type:DataTypes.STRING, allowNull:false},
        hashedPassword:{type:DataTypes.STRING,allowNull:false}
    });

But I am getting this error:

Type 'ModelCtor<Model<any, any>>' is missing the following properties from type 'Model<any,any>': _attributes, _creationAttributes, isNewRecord, where, and 16 more.

But if I do this:

const User:any= db.define('User',{
    id: {type:DataTypes.INTEGER, primaryKey:true},
    email:{type:DataTypes.STRING, allowNull:false},
    hashedPassword:{type:DataTypes.STRING,allowNull:false}
});

It works fine. But of course, because this is TypeScript, I want to take advantage of Types. Using "any" defeats the purpose. How can I know which type I should use for my model? Unfortunately, most of sequelize's documentation is regular javascript, so I can't find examples of this. Any help is appreciated.

like image 985
tutiplain Avatar asked Oct 31 '25 09:10

tutiplain


1 Answers

From the manual

Since v5, Sequelize provides its own TypeScript definitions. Please note that only TS >= 3.1 is supported.

As Sequelize heavily relies on runtime property assignments, TypeScript won't be very useful out of the box. A decent amount of manual type declarations are needed to make models workable.

You can find the usage of sequelize.define with TypeScript at the bottom of the doc.

E.g. "sequelize": "^5.21.3"

user.ts:

import { Sequelize, DataTypes, Model, BuildOptions } from 'sequelize';

const db = new Sequelize('mysql://root:asd123@localhost:3306/mydb');

interface UserAttributes {
  readonly id: number;
  readonly email: string;
  readonly hashedPassword: string;
}
interface UserInstance extends Model<UserAttributes>, UserAttributes {}
type UserModelStatic = typeof Model & {
  new (values?: object, options?: BuildOptions): UserInstance;
};

const User = db.define('User', {
  id: { type: DataTypes.INTEGER, primaryKey: true },
  email: { type: DataTypes.STRING, allowNull: false },
  hashedPassword: { type: DataTypes.STRING, allowNull: false },
}) as UserModelStatic;

(async function test() {
  const user: UserInstance = await User.create({
    id: 1,
    hashedPassword: '123',
    email: '[email protected]',
  });
  user.getDataValue('email');
})();
like image 173
slideshowp2 Avatar answered Nov 02 '25 23:11

slideshowp2