声明Partial<T>后仍报Cannot read property of undefined的问题排查
排查
Cannot read property 'endTime' of undefined错误原因 错误根源
这个错误的核心是运行时传入的interaction参数为undefined,具体细节:
Partial<InteractionTypeInteractionMap[T]>的类型声明仅约束对象的属性为可选,但并未限制参数本身不能是undefined或null。TypeScript的类型检查仅在编译阶段生效,无法阻止运行时传入不符合预期的值。- 当调用
mapOptionsToEditActivity时,如果传入的interaction是undefined,运行时访问interaction.endTime就会触发该报错。
解决方案
针对这个问题,可从以下方向处理:
1. 编译+运行时双重校验参数非空
修改参数类型明确禁止传入undefined,同时添加运行时兜底校验:
export function mapOptionsToEditActivity<T extends InteractionType>( interaction: NonNullable<Partial<InteractionTypeInteractionMap[T]>>, interactionType: T, matchedRecord: InteractionMatchedRecord, user: User, activityId: string, ): Partial<CrmInteraction> { if (!interaction) { throw new Error("interaction参数不能为空"); } const mappedInteraction = { crmCallId: activityId, dateEnd: interaction.endTime, dateStart: interaction.startTime, userCrmId: user.crmId, }; return mappedInteraction; }
2. 用可选链避免报错(允许参数为undefined)
如果业务场景允许interaction为undefined,使用可选链操作符?.规避报错:
const mappedInteraction = { crmCallId: activityId, dateEnd: interaction?.endTime, dateStart: interaction?.startTime, userCrmId: user.crmId, };
此时interaction为undefined时,dateEnd和dateStart会被设为undefined,符合返回值Partial<CrmInteraction>的类型要求。
3. 给参数设置默认空对象
如果调用方可能遗漏该参数,给interaction设置默认值:
export function mapOptionsToEditActivity<T extends InteractionType>( interaction: Partial<InteractionTypeInteractionMap[T]> = {}, interactionType: T, matchedRecord: InteractionMatchedRecord, user: User, activityId: string, ): Partial<CrmInteraction> { const mappedInteraction = { crmCallId: activityId, dateEnd: interaction.endTime, dateStart: interaction.startTime, userCrmId: user.crmId, }; return mappedInteraction; }
内容的提问来源于stack exchange,提问作者AnanR
相关产品推荐
相关产品推荐

