【发布时间】:2021-08-27 18:13:15
【问题描述】:
我需要使用接口的属性指定函数的类型(通常需要使用接口定义模块的 API),但是 ts 抱怨返回类型,似乎它只考虑了一种类型定义,因为抱怨返回不正确类型:
export interface DateWrapper {
isSame(firstDate: DateType, secondDate: DateType): boolean;
isSame(firstDate: DateType): (secondDate: DateType) => boolean;
}
export const isSame: DateWrapper['isSame'] = (
firstDate: DateType,
secondDate?: DateType,
) => {
if (!secondDate) {
return (secondDate_: DateType) =>
areDatesEqueal(firstDate, secondDate_);
}
return areDatesEqueal(firstDate, secondDate);
};
这是来自 ts 的错误:
Type 'boolean | ((secondDate_: DateType) => boolean)' is not assignable to type 'boolean'
使用function declaration 指定重载可以解决问题,但我需要使用接口属性。
【问题讨论】:
标签: typescript function interface overloading