推断回调参数的类型

时间:2020-10-10 10:17:54

标签: typescript type-inference typescript-generics

我无法让编译器知道回调参数的类型。

{'_id': '123XYZ',
 'location': [{'date1': [54, 64]},
              {'date2': [34, 44]},
              {'date3': [30, 40]},
              {'date4': [50, 60]}]}

我不明白为什么在第二次通话中,我必须手动编写foo的类型,而不必在第一次通话中。

推断是否可以处理这些重载?如果是,怎么办?如果没有,为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

// change the order for more specific type first
function test3(fn: (foo: string, payload: number) => any): any;
function test3(fn: (foo: string) => any): any;
function test3(fn: (foo: string, payload: number) => any) {

}

test3((foo) => 1);
test3((foo, payload) => 1);

Playground