sequelize-typescript icon indicating copy to clipboard operation
sequelize-typescript copied to clipboard

`order` property not assignable to `FindOptions` if stored in a variable

Open Tchekda opened this issue 2 years ago • 1 comments

Issue

When passing FindOptions through a variable instead of defining them in the function call, typescript throws an error.

Versions

  • sequelize: 6.32.1
  • sequelize-typescript: 2.1.5
  • typescript: 4.9.5

Issue type

  • [x] bug report
  • [ ] feature request

Actual behavior

When passing FindOptions directly to findAll, findByPk, fondOne, ..., everything works as expected:

return MyModel.findAll({
  where: { modelId: id},
  attributes: {
    exclude: ['created_at', 'updated_at', 'context']
  },
  include: [ /* Multiple includes */ ],
  order: [
    ['COL_X', 'DESC'],
    [sequelize.col('`INCLUDE_1`.`order`'), 'ASC'],
    [sequelize.col('`INCLUDE_2`.`order`'), 'ASC'],
    [sequelize.col('`INCLUDE_3`.`order`'), 'ASC']
  ],
  subQuery: false,
})

But when I pass those options as a spread variable, I get this :

// Meant to be reused across multiple calls of .findAll, .findOne, .findByPk
const QUERY = {
  where: { modelId: id},
  attributes: {
    exclude: ['created_at', 'updated_at', 'context']
  },
  include: [ /* Multiple includes */ ],
  order: [
    ['COL_X', 'DESC'],
    [sequelize.col('`INCLUDE_1`.`order`'), 'ASC'],
    [sequelize.col('`INCLUDE_2`.`order`'), 'ASC'],
    [sequelize.col('`INCLUDE_3`.`order`'), 'ASC']
  ],
  subQuery: false,
};

return MyModel.findAll(QUERY);
Argument of type '{ attributes: { exclude: string[]; }; include: ({ model: typeof INCLUDE_MODEL_1; as: string; required: boolean; attributes: string[]; through: { attributes: any[]; }; } | { model: typeof INCLUDE_MODEL_2; as: string; required: boolean; attributes: string[]; through: { ...; }; } | { ...; } | { ...; })[]; ord...' is not assignable to parameter of type 'FindOptions<MyModelAttributes>'.
  Types of property 'order' are incompatible.
    Type '(string | Col)[][]' is not assignable to type 'Order'.
      Type '(string | Col)[][]' is not assignable to type 'OrderItem[]'.
        Type '(string | Col)[]' is not assignable to type 'OrderItem'.
          Type '(string | Col)[]' is not assignable to type '[OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemAssociation, OrderItemColumn, string]'.
            Target requires 6 element(s) but source may have fewer.

For now I have to add @ts-ignore above the function call to silent those errors, and the queries work perfectly as they match the sequelize expected format

Expected behavior

Have the typing work the same way of the options are passed directly or through a variable

Tchekda avatar Oct 18 '23 20:10 Tchekda

This issue is still alive. We end up with a lot of those in our codebase.

const users = await models.user.findAll({
    ...queryOptions,
    order: [['id', 'ASC']]
  })

vincentdesmares avatar Jan 02 '25 10:01 vincentdesmares