How to type aggregate functions using Sequelize

Viewed 286

I am working on running a simple query to sum a column value, it works pretty good but I was wanting to know if there is way to type the result somehow, I am using type-script and I'd really like to avoid the //@ts-ignore part. This is how my code looks like:

const result: number = parseInt(
        (
          await Model.findAll({
            attributes: [
              [Sequelize.fn('sum', Sequelize.col('amount')), 'total']
            ],
            where: {
              any-criteria
            }
          })
        )[0]['dataValues']['total'] ?? 0,
        10
      )

I was wondering if there is a way to do something like:

const result: number = 
          await Model.findAll({
            attributes: [
              [Sequelize.fn('sum', Sequelize.col('amount')), 'total']
            ],
            where: {
              any-criteria
            }
          })
        )
1 Answers

You have to force cast typeof Model to unknown type first, after then you can convert it to any type like this.

 const result = ((
    await Model.findAll({
      attributes: [
        [Sequelize.fn('sum', Sequelize.col('amount')), 'total']
      ],
      where: {
        any-criteria
      }
    })
  )[0]['dataValues']['total'] ?? 0) as unknown as number
Related