You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Underscore _.sortBy转原生JS .sort()遇TS2362错误求助

解决TypeScript中使用原生sort排序Date时的TS2362错误

你遇到这个TS2362错误的核心原因是TypeScript的严格类型检查不允许直接对Date对象进行算术减法运算——虽然在原生JavaScript里,Date对象相减会自动转换为时间戳数值,但TypeScript需要你明确告诉它要处理的是数值类型,否则就会抛出类型错误。

问题拆解

Underscore的_.sortBy内部帮你做了隐式转换:它会把你返回的Date对象自动处理成可用于排序的比较值。但原生Array.sort()的回调函数在TypeScript中,要求返回值必须是明确的number类型,直接用new Date(...) - new Date(...)会让TypeScript认为你在对两个Date对象做减法,不符合它的类型规则,因此触发错误。

修复方案

最直接的解决方法是显式将Date对象转换为时间戳数值,使用Date.getTime()方法,这样TypeScript就能识别出这是合法的数值运算:

// 推荐的修复代码
this.interviewDetails.data.sort((a, b) => {
  const timeA = new Date(a.timeslot).getTime();
  const timeB = new Date(b.timeslot).getTime();
  return timeA - timeB;
});

进阶优化(类型安全)

另外,尽量避免用any类型,给你的数据定义明确的接口,这样能充分利用TypeScript的类型检查优势:

// 先定义数据类型
interface InterviewItem {
  timeslot: string; // 或者根据实际情况设为Date类型
  // 其他字段比如id、interviewerName等
}

// 然后排序时指定类型
(this.interviewDetails.data as InterviewItem[]).sort((a, b) => {
  const timeA = new Date(a.timeslot).getTime();
  const timeB = new Date(b.timeslot).getTime();
  return timeA - timeB;
});

额外处理:无效日期

如果timeslot可能存在无效的日期字符串,导致getTime()返回NaN,可以加个兜底处理,避免排序出现异常:

this.interviewDetails.data.sort((a, b) => {
  const timeA = new Date(a.timeslot).getTime() || 0; // 无效日期设为0,会排在最前面
  const timeB = new Date(b.timeslot).getTime() || 0;
  return timeA - timeB;
});

内容的提问来源于stack exchange,提问作者Yashwardhan Pauranik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:57:35