如何通过interface属性指定重载函数类型解决TS返回值报错
TypeScript interface函数属性重载实现方案
报错根因
TypeScript 对箭头函数的重载支持有限:当你直接为箭头函数标注包含多重重载的接口属性类型时,TS不会逐重载匹配实现逻辑,只会统一将返回值推断为boolean | ((secondDate: DateType) => boolean)联合类型,无法匹配重载签名要求的单个返回值类型,因此抛出类型错误。
解决方案
方案1:类型断言(快速修复)
你可以在函数实现末尾显式断言为目标接口属性类型,TS会直接接受实现符合重载要求,调用时的类型提示也不会丢失:
// 接口定义保持不变 export interface DateWrapper { isSame(firstDate: DateType, secondDate: DateType): boolean; isSame(firstDate: DateType): (secondDate: DateType) => boolean; } export const isSame = ( firstDate: DateType, secondDate?: DateType, ) => { if (!secondDate) { return (secondDate_: DateType) => areDatesEqueal(firstDate, secondDate_); } return areDatesEqueal(firstDate, secondDate); } as DateWrapper['isSame']; // 新增类型断言
方案2:显式函数重载赋值(类型更安全)
如果不想用类型断言避免潜在类型风险,可以先用函数声明的方式写重载实现,再赋值给符合接口类型的常量,完全满足你用interface定义API的要求:
// 接口定义保持不变 export interface DateWrapper { isSame(firstDate: DateType, secondDate: DateType): boolean; isSame(firstDate: DateType): (secondDate: DateType) => boolean; } // 先写函数声明重载实现 function isSameImpl(firstDate: DateType, secondDate: DateType): boolean; function isSameImpl(firstDate: DateType): (secondDate: DateType) => boolean; function isSameImpl(firstDate: DateType, secondDate?: DateType) { if (!secondDate) { return (secondDate_: DateType) => areDatesEqueal(firstDate, secondDate_); } return areDatesEqueal(firstDate, secondDate); } // 赋值给符合接口类型的常量 export const isSame: DateWrapper['isSame'] = isSameImpl;
内容的提问来源于stack exchange,提问作者Oleksandr Sakun
相关产品推荐
相关产品推荐

