Search code examples
typescriptsequelize.js

Add Static Method to Sequelize Model Abstract Class with Typescript


When working with Sequelize, I found it helpful to add static methods to all Models. In Javascript I would simply assign the method in the following way:

const { Model } = require('sequelize)

Model.someStaticMethod = () => {}

However, in Typescript, this will cause an error as someStaticMethod is not defined on the abstract class Model.


Solution

  • In order to get around this, you can create variables within a given namespace, thereby allowing you to augment the class and add static methods.

    // types/sequelize/index.d.ts
    
    import 'sequelize'
    
    declare module 'sequelize' {
      namespace Model {
        let someStaticMethod : function // You can import the actual function definition here.
      }
    }
    

    Now when assigning Model.someStaticMethod = () => {}, Typescript will no longer throw an error.

    Hope this helps someone out!