TypeScript按日期排序不起作用 [英] TypeScript sort by date not working
问题描述
我有一个对象TaskItemVO
,其字段为dueDate
,类型为Date
:
I have an object TaskItemVO
with field dueDate
which has the type Date
:
export class TaskItemVO {
public dueDate: Date;
}
我有这种方法,当我尝试按日期排序但不起作用时:
I have this method which I call when I try to sort by date but it is not working:
public sortByDueDate(): void {
this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => {
return a.dueDate - b.dueDate;
});
}
我在方法的返回行中收到此错误:
I get this error in the return line of method:
算术运算的右侧必须为'any','number'或枚举类型.
The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
算术运算的左侧必须为'any','number'或枚举类型.
The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
那么在TypeScript中按日期字段对数组进行排序的正确方法是什么?
推荐答案
尝试使用 ^上面的错误引发了带有未定义日期的错误,请尝试以下操作:
^ Above throws error with undefined date so try below:
如果要处理未定义的内容:
If you want to handle undefined:
private getTime(date?: Date) {
return date != null ? date.getTime() : 0;
}
public sortByDueDate(): void {
this.myArray.sort((a: TaskItemVO, b: TaskItemVO) => {
return this.getTime(a.dueDate) - this.getTime(b.dueDate);
});
}
这篇关于TypeScript按日期排序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!