typescript - 传递给通用函数包装器(如 _.debounce)的函数的类型推断

标签 typescript type-inference typescript-generics

在 TypeScript 中,如果将函数表达式作为参数传递,则可以完美地推断出其参数的类型:

var foo = (fn: (a: string) => void) => {};

foo(a => { 
    // a is inferred to be a string
    alert(a.toLowerCase());
});

对于事件处理程序和其他回调来说真的很方便。但是,如果函数表达式被包装在通用包装函数的调用中,该函数将函数作为参数并返回具有相同签名(返回值除外)的函数,例如_.debounce在 Lodash 中,推理不会发生。

var debounce = <T>(fn: (a: T) => void) => {
    return (a: T) => { /* ... */ };
};

foo(debounce(a => { 
    // a is inferred to be {}
    // type error: 'toLowerCase' doesn't exist on '{}'
    alert(a.toLowerCase());
}));

TS Playground

作为foo希望它的参数是 (a: string) => void ,编译器可以尝试为 T 找到这样的类型那debounce<T>会返回 (a: string) => void .但它不会尝试这样做。

我错过了什么吗?我应该为 debounce 写类型注释吗?不知何故?是设计使然吗? GitHub 上有关于这个案例的问题吗?

2017 年更新:现在可以使用了! TS 2.5。

最佳答案

首先,当您调用不带类型参数的泛型函数时,编译器必须确定每个类型参数的类型。

因此,当您调用debounce 时,编译器必须找到T 类型的候选项。但是 debounce 唯一可以从中得出推论的地方是您的函数,而您没有为您的类型参数提供明确的类型。

因此编译器认为它没有任何类型可供使用,并回退到 {}(“空类型”,通常简称为“curly curly”) T.

整个过程称为类型参数推断

然后编译器会注意到您没有为箭头函数的参数指定类型。它不是默认为 any,而是认为它可以从 debounce 的参数类型中找出来。此过程称为上下文打字

嗯,fn 的类型基本上是 (a: {}) => void,所以编译器认为“好吧,很好,我们可以给 a 一种类型!”不幸的是,它最终成为……{}


因此,虽然这不是绝对的好,但修复并不是那么糟糕。只需为 a 添加类型注释:

foo(debounce((a: string) => { 
    // Everything is fine!
    alert(a.toLowerCase());
}));

或者使用类型参数:

foo(debounce<string>(a => { 
    // Everything is fine!
    alert(a.toLowerCase());
}));

关于typescript - 传递给通用函数包装器(如 _.debounce)的函数的类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35613446/

相关文章:

将接口(interface)或类型分配给 Record<string, string> 的 typescript

angular - typescript :引用变量中的接口(interface)

TypeScript:使用数组获取深度嵌套的属性值

斯卡拉拼图 : enforcing that two function arguments are of the same type AND both are a subtype of a given class

typescript - 推断列数组中 rowData 和 cellData 的类型

asp.net-mvc - 如何将 signalr 集成到 typescript 项目中?

Scala:如何定义 "generic"函数参数?

haskell - 为什么 ghci 输出 (Num a) => a for :t 4 and not (Ord a) => a?

typescript :T 扩展字符串 |数字=字符串?

typescript - 映射到对象的元组数组不会产生正确的值