How can I tell typescript that the getAssociation function exists in a Sequelize model?

404 views Asked by At

I have the following code:

interface TableBAttributes {
    TableBId: number;
}

interface TableAAttributes {
    TableAId: number;
    TableB: TableB;
}

class TableA extends Model<TableAAttributes> {}
TableA.init({
   TableAId: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      allowNull: false,
      autoIncrement: true
   },
   TableB: {
      DataTypes.INTEGER,
      references: {
         model: TableB,
         key: 'tableB_id'
      },
      field: 'tableB_id'
   }
}, {
  sequelize,
  modelName: 'TableA',
  tableName: 'TableA'
});

TableA.belongsTo(TableB, {
   foreignKey: 'tableB_id',
   as: 'TableB'
});

class TableB extends Model<TableBAttributes> {};
TableB.init({
    TableBId: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true
    }
}, {
   sequelize,
   modelName: 'TableB',
   tableName: 'TableB'
});

(async () => {
   const test = await TableA.findByPk(1);
   const relatedTableB = await test.getTableB();
   console.log(relatedTableB);
})();

If I run this code, everything works correctly, and I get back the associated TableB from my query. My only problem is, that typescript complains that the test.getTableB() function does not exist, as this method is created by Sequelize.

How could I tell typescript that this method exists?

1

There are 1 answers

0
Shivam Singla On BEST ANSWER

Check this if it works for you.

For more info

import {
  Model,
  HasOneGetAssociationMixin,
} from "sequelize";

interface TableBAttributes {
  TableBId: number;
}

interface TableAAttributes {
  TableAId: number;
}

class TableA extends Model<TableAAttributes> {
  public getTableB!: HasOneGetAssociationMixin<TableB>
}

class TableB extends Model<TableBAttributes> { }

TableA.belongsTo(TableB, {
  foreignKey: 'tableB_id',
  as: 'TableB'
});

(async () => {
  const test = await TableA.findByPk(1);
  const relatedTableB = await test.getTableB();
  console.log(relatedTableB);
})();