const enum Tag {
Friday = 'Friday',
Planning = 'Planing',
}
const test = (tag: Tag, todo:/* ??? */): string => {/* some logic */}
当tag
为Tag.Friday
时,todo
应该为(tour: string) => string
当tag
为Tag.Planning
时,todo
应该为(date: Date) => string
我尝试了区分函数的联合和函数重载,但它们都不能推断todo
类型。 TS Playground
答案 0 :(得分:0)
如果将函数声明为接口,则可以在TypeScript中使用函数重载。
例如:
const enum Tag {
Friday = 'Friday',
Planning = 'Planing',
}
type TourFunc = (tour: string) => string
type DateFunc = (date: Date) => string
interface Fn {
(tag: Tag.Friday, todo: TourFunc): string;
(tag: Tag.Planning, todo: DateFunc): string;
}
const test: Fn = (tag: Tag, todo: TourFunc | DateFunc): string => {
return 'a';
}
const dateFunc : DateFunc = (a: Date) => a.toDateString()
const tourFunc : TourFunc = (b: string) => b
test(Tag.Planning, (s: string) => 'a'); // Error
test(Tag.Planning, dateFunc); // Ok
test(Tag.Friday, tourFunc); // Ok
test(Tag.Planning, tourFunc); // Error