Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript & Sequelize: Pass in generic Model

I have this code

import { Model, DataTypes, Sequelize } from "sequelize";

class User extends Model {
    public id!: number;
    public firstName!: string;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;
}

function async InitAndDefineModel(model: Model): void {
    const sequelize = new Sequelize({
        dialect: "sqlite",
        storage: ":memory:",
    });
    model.init{
        firstName: {
            allowNull: false,
            type: DataTypes.STRING,
        },
    },
    {
        sequelize,
    });
    const tables = await sequelize.showAllSchemas({});
    console.log(tables);
}

InitAndDefineModel(User);

The console.log statement returns:

// [ { name: 'Users' } ]

So I know the code works, however, TypeScript complains that:

Property 'init' is a static member of type 'Model<any, any>'ts(2576)

on the model.init(...) call.

I think TS thinks I'm passing in a Model object directory. I guess I need to tell it it's a type of Model, or the object passed in was extended from it. How do I tell TypeScript that the argument model: Model is valid? I tried to use model: Model<T> and `model: T any other variations, but to no avail.

like image 991
MorganR Avatar asked Oct 29 '25 21:10

MorganR


1 Answers

You should create a static type representation of your models like:

type ModelStatic = typeof Model & {
  new(values?: object, options?: Sequelize.BuildOptions): Model;
}

And you could define the InitAndDefineModel function like this:

function async InitAndDefineModel(model: ModelStatic): void

In such a case the model passed to above function should now allow to access static methods of Sequelize.Model

like image 62
piotrbienias Avatar answered Nov 01 '25 11:11

piotrbienias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!