函数变量重载

时间:2017-01-24 08:44:46

标签: typescript overloading currying

我有一个curried函数,我需要重载返回的函数签名(简化示例):

const foo = (bar: string) => (tag: string, children?: string[]) => {
const foo = (bar: string) => (tag: string, props: Object, children?: string[]) => {
  // Do something
};

重载在使用function关键字的类方法或函数声明时效果很好,但我无法使用curried函数。

1 个答案:

答案 0 :(得分:3)

你可以这样做:

type MyCurriedFunction = {
    (tag: string, children?: string[]): void;
    (tag: string, props: Object, children?: string[]): void;
}

const foo = (bar: string): MyCurriedFunction => (tag: string, ...args: any[]) => {
    // do something
}

foo("str")("tag", ["one", "two"]); // fine
foo("str")("tag", {}, ["one", "two"]); // fine
foo("str")("tag", ["one", "two"], {}); // error

code in playground