我无法让编译器知道回调参数的类型。
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 的类型,但在第一次调用时却不需要。
推断可以处理这些重载吗?如果是,如何?如果不是,为什么它不起作用?
最佳答案
// 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);
关于typescript - 推断回调参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64292338/