I am working on a legacy project that we would like to migrate to Typescript. It has models defined in the following format:
import Sequelize from "sequelize";
class MyModel extends Sequelize.Model {
public static init(sequelize) {
const attributes = {
userId: {
type: Sequelize.INTEGER,
allowNull: false,
field: "user_id"
},
createdAt: {
type: Sequelize.DATE,
field: "created_at"
}
};
super.init(attributes, {
sequelize
});
}
}
export default MyModel;
I would like to convert them to typescript without having to change the interface for consumers. By that I mean I want to extend Sequelize.Model
and I want to define a public static init
method.
I am getting the following error from Typescript on Sequelize.Model
Type 'Model<any, any>' is not a constructor function type.
And all of the research I've done points to using Sequelize.define
to define models.
This being a legacy project I don't want to re-write all of my models just to conform to the types so I'm wondering how I can properly extend Sequelize.Model
?
Thanks
You can also connect different types of databases to your project while using the same code to access them. In this article, you'll learn how to use the Sequelize ORM with TypeScript. So grab your laptops, open your IDE, and let's get started!
The Model.update() method will update your table rows with the values you passed as its first argument. The syntax of the method is as shown below: Model. update( { // values }, { // options } );
A model can be synchronized with the database by calling model.sync(options) , an asynchronous function (that returns a Promise). With this call, Sequelize will automatically perform an SQL query to the database. Note that this changes only the table in the database, not the model in the JavaScript side.
With timestamps: false , the generated model will omit the createdAt and updatedAt attributes. You can also opt to include only the timestamp attribute you need as shown below: const User = sequelize. define( "User", { firstName: Sequelize.
Try This
public static init(sequelize) {
super.init.call(this,{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
text: {
type: DataTypes.STRING(5000) // extra long length
}
}, {
sequelize: sequelize
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With