My goal is to retrieve all records from a MySql table that were created within a specific date range.
To accomplish this, I created the following code snippet:
import { Sequelize, Model, DataTypes, Op } from 'sequelize';
const sequelize = new Sequelize({
// database connection configuration
dialect: 'mysql'
})
class Patient extends Model {
public guid!: number;
public name!: string;
public recordState: number = 0;
public createdAt?: Date;
public updatedAt?: Date
}
Patient.init({
guid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false
},
name: { type: DataTypes.STRING, allowNull: false },
recordState: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE
}, {
sequelize,
modelName: 'Patient',
timestamps: false
})
Patient.findAll({
where: {
createdAt: {
[Op.between]: [new Date('2020-02-02'), new Date()]
}
}
})
However, during compilation using tsc
, an error was reported:
sequelize.ts:50:5 - error TS2322: Type '{ [between]: Date[]; }' is not assignable to type 'string | number | boolean | WhereAttributeHash | AndOperator | OrOperator | Literal | Where | Fn | Col | WhereOperators | Buffer | WhereGeometryOptions | (string | ... 2 more ... | Buffer)[]'.
Types of property '[Op.between]' are incompatible.
Type 'Date[]' is not assignable to type 'string | number | boolean | [number, number] | WhereAttributeHash | AndOperator | OrOperator | Literal | Where | ... 5 more ... | (string | ... 2 more ... | Buffer)[]'.
Type 'Date[]' is not assignable to type '(string | number | WhereAttributeHash | Buffer)[]'.
Type 'Date' is not assignable to type 'string | number | WhereAttributeHash | Buffer'.
Type 'Date' is not assignable to type 'WhereAttributeHash'.
Index signature is missing in type 'Date'.
50 createdAt: {
~~~~~~~~~
Found 1 error.
This error suggests that using Op.between
with a date range might not be supported in TypeScript. Strangely, it worked fine when implemented in JavaScript.
I am unsure if there is a flaw in my TypeScript code, a deficiency in the type definition, or if utilizing Op.between
with dates is discouraged.