typescript - 推断回调参数的类型

标签 typescript type-inference typescript-generics

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

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

Playground

关于typescript - 推断回调参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64292338/

相关文章:

typescript - 确定类型是 'string' 文字、 'number' 文字还是 'string | number' 文字

generics - 在应用程序 : problem with type inference 之前选择函数引用

compiler-errors - 找到预期的 XYZ ()

typescript - 为什么 TypeScript 允许在具有不同参数类型的自定义泛型类型之间进行分配?

typescript - 扩展 'generic' TypeScript 接口(interface)

javascript - Angular 2 应用程序转移到服务层后逻辑无法正常工作

java - Angular 4 : How to build for production without losing resposive design meta tags.

Angular 2 - 替换历史而不是推送

haskell - 什么是单态性限制?

typescript - 如何使用字符串联合填充对象类型的可选嵌套关系?