繁体   English   中英

推断回调参数的类型

[英]Infer type of callback argument

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

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

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM