本文介绍了在带日期的序列中使用Op.between时出现TypeScript错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在某个日期范围内创建的MySql表中查找所有记录.
I want to find all records in a MySql table which was created within a certain range of date.
所以我写道:
import { Sequelize, Model, DataTypes, Op } from 'sequelize';
const sequelize = new Sequelize({
// some db connection config
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()]
}
}
})
但是,当我尝试使用 tsc
进行编译时,它会报告如下错误:
But, when I try to compile it with tsc
, it reports error like:
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.
似乎我不能在日期范围内使用 Op.between
?但是当我用JS编写类似的代码时就可以了.
It seems I cannot use Op.between
with a date range? But it's ok when I wrote similar code in JS.
所以我想知道我的TS代码中是否确实存在某些问题,或者类型定义中仅缺少一项,还是不建议将 Op.between
与日期一起使用?
So I wonder if there is really something wrong in my TS code or just a missing in the type definition, or maybe using Op.between
with dates is not recommended?
推荐答案
您正在传递日期对象而不是字符串.这样做:
You're passing a date object instead of a string. Do this:
Patient.findAll({
where: {
createdAt: {
[Op.between]: [new Date('2020-02-02').toISOString(), new Date().toISOString()]
}
}
})
这篇关于在带日期的序列中使用Op.between时出现TypeScript错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!