typescript - 推断回调参数的类型
问题描述
我无法让编译器知道回调参数的类型。
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);
推荐阅读
- c++ - 从自动售货机退回硬币
- javascript - 如何从 Square 的交易哈希中获取记录表?
- python - 如何解决“参数 Z 必须是二维的”
- r - 为什么 glmmTMP 估计模拟数据的零膨胀康威麦克斯韦泊松混合模型的大约一半值
- java - 用java推荐电影
- python - Python PANDAS:将函数应用于数据帧,并在数据帧中定义参数
- javascript - 创建函数字符串样板
- python - Python:将 SSML 与 SAPI 结合使用(comtypes)
- javascript - 如何在对象页面布局的块视图中将 oData 模型绑定到表?
- java - 为什么 AuthenticationFilter 完成后 RestController 不接收请求