首页 > 解决方案 > 推断回调参数的类型

问题描述

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

function test3(fn: (foo: string) => any): any;
function test3(fn: (foo: string, payload: number) => any): any;
function test3(fn: (foo: string, payload: number) => any) {

}

test3((foo) => 1); // Ok, typescript knows "foo" is a string
test3((foo, payload) => 1); // KO, typescript does not infer "foo" nor "payload" type

我不明白为什么在第二次调用时,我必须手动编写 foo 的类型,但不是在第一次调用中。

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

标签: typescripttype-inferencetypescript-generics

解决方案


// 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);

操场


推荐阅读