Angular 14+日历分组事件报错:eventGroups不存在于MonthViewDay类型
Angular 14+ 日历分组事件类型错误解决方法
你遇到的TypeScript错误本质是两个问题:一是CalendarMonthViewDay<EventGroupMeta>类型本身没有eventGroups属性,直接赋值触发了类型检查;二是groups变量未初始化,会导致运行时异常。以下是具体修复步骤:
1. 扩展日历日期单元格的类型定义
创建自定义类型,给默认的CalendarMonthViewDay添加eventGroups属性,让TypeScript识别这个新增属性:
import { CalendarMonthViewDay, CalendarEvent } from 'angular-calendar'; // 你的EventGroupMeta类型(根据实际业务调整) interface EventGroupMeta { type: string; } // 扩展MonthViewDay,新增eventGroups属性 interface ExtendedMonthViewDay extends CalendarMonthViewDay<EventGroupMeta> { eventGroups?: [string, CalendarEvent<EventGroupMeta>[]][]; }
2. 修正beforeMonthViewRender方法逻辑
把方法参数的body类型替换为自定义的ExtendedMonthViewDay[],同时初始化groups变量避免undefined错误:
beforeMonthViewRender({ body, }: { body: ExtendedMonthViewDay[]; }): void { body.forEach((cell) => { // 初始化groups为空对象,避免后续赋值时的undefined报错 const groups: Record<string, CalendarEvent<EventGroupMeta>[]> = {}; cell.events.forEach((event: CalendarEvent<EventGroupMeta>) => { const eventType = event.meta?.type; if (eventType) { groups[eventType] = groups[eventType] || []; groups[eventType].push(event); } }); // 现在可以直接赋值,类型检查通过 cell.eventGroups = Object.entries(groups); }); }
3. 模板中安全使用eventGroups
在模板里遍历分组事件时,确保类型兼容(示例):
<ng-template #monthCellTemplate let-day="day"> <div *ngIf="day.eventGroups"> <div *ngFor="let group of day.eventGroups"> <h6>{{ group[0] }}</h6> <div *ngFor="let event of group[1]" class="event-item"> {{ event.title }} </div> </div> </div> </ng-template>
这样修改后,TypeScript的类型错误会消失,同时也避免了groups未初始化导致的运行时问题。
内容的提问来源于stack exchange,提问作者Enrico
相关产品推荐
相关产品推荐

