基于ES6函数式风格检测日期间隔差异时遇reduce类型错误
问题分析与修复
你的代码里reduce出现类型错误,主要有以下几个问题:
- 语法错误:回调函数的括号闭合错误,多写了一个右括号,导致代码结构混乱
- 类型不匹配:
reduce的初始值是{endDate: currentDate}(对象类型),但回调函数返回的是differenceInDays的结果(数值类型),TypeScript会因为返回值类型不一致报错 - 排序逻辑错误:
sort的回调函数使用isSameOrBefore返回布尔值,但sort要求返回-1 | 0 | 1的数值类型,排序结果会不符合预期 - 需求实现偏差:如果要计算每两个相邻日期段的间隔天数,你的
reduce写法没有正确累积结果
修复后的代码示例
先修正排序逻辑
使用date-fns的compareAsc函数来正确排序日期段(或者手动转换日期比较):
const sorted = segments.sort((a, b) => compareAsc(new Date(a.startDate), new Date(b.startDate)));
场景1:收集所有相邻日期段的间隔天数
如果需要得到所有间隔天数的数组:
// 计算所有相邻段的间隔天数 const gaps = sorted.reduce((acc, current, index) => { // 跳过第一个元素,没有前一段 if (index === 0) return acc; const previousSegment = sorted[index - 1]; // 计算当前段开始与上一段结束的天数差 const gapDays = differenceInDays( new Date(current.startDate), new Date(previousSegment.endDate) ); acc.push(gapDays); return acc; }, [] as number[]);
场景2:判断所有日期段是否符合间隔条件
如果你的目标是判断所有日期段的间隔是否符合要求(比如间隔天数≥0,无重叠):
// 判断所有相邻段的间隔是否符合要求(示例:间隔≥0,即当前段开始不早于上一段结束) const isValidSegments = sorted.every((current, index) => { if (index === 0) return true; const previousSegment = sorted[index - 1]; const gapDays = differenceInDays( new Date(current.startDate), new Date(previousSegment.endDate) ); // 这里可以替换成你的具体条件,比如gapDays <= 30等 return gapDays >= 0; });
完整修复后的isValid函数
type DateSegment = { startDate: string; endDate: string }; // ISO 8601 timestamps const isValid = (current: ResidentialAddress, history: Array<ResidentialAddress>): boolean => { if (!current || history.length === 0) return false; const currentDate = formatInTimeZone(new Date(), 'UTC', 'yyyy-MM-dd'); // 转换为日期段数组 const segments: DateSegment[] = [ { startDate: current.startDate, endDate: currentDate }, ...history.map(x => ({ startDate: x.startDate, endDate: x.endDate })) ]; // 正确排序日期段 const sorted = segments.sort((a, b) => compareAsc(new Date(a.startDate), new Date(b.startDate))); // 这里以判断所有间隔≥0为例,你可以替换成自己的条件 const isValidSegments = sorted.every((currentSeg, index) => { if (index === 0) return true; const prevSeg = sorted[index - 1]; const gap = differenceInDays(new Date(currentSeg.startDate), new Date(prevSeg.endDate)); // 示例条件:间隔≥0,无重叠且顺序正确 return gap >= 0; }); console.log(isValidSegments); return isValidSegments; };
内容的提问来源于stack exchange,提问作者Luke Martin
相关产品推荐
相关产品推荐

