打字稿中区分的功能

时间:2020-07-06 06:22:28

标签: typescript overloading discriminated-union

const enum Tag {
  Friday = 'Friday',
  Planning = 'Planing',
}
const test = (tag: Tag, todo:/* ??? */): string => {/* some logic */}

tagTag.Friday时,todo应该为(tour: string) => string

tagTag.Planning时,todo应该为(date: Date) => string

我尝试了区分函数的联合和函数重载,但它们都不能推断todo类型。 TS Playground

1 个答案:

答案 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

Playground Link