传递给通用函数包装器的函数的类型推断,如 _.debounce

Type inference for functions passed to generic function wrappers like _.debounce

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

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

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

对于事件处理程序和其他回调来说真的很方便。但是,如果函数表达式被包装在通用包装函数的调用中,该函数将函数作为参数并且 returns 是具有相同签名的函数(return 值除外),例如_.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> 会 return (a: string) => void。但它不会尝试这样做。

我错过了什么吗?我是否应该以其他方式为 debounce 编写类型注释?是设计使然吗?关于这个案例 GitHub 有问题吗?

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

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

因此,当您调用 debounce 时,编译器必须找到 T 类型的候选者。但是 debounce 唯一可以推断的地方是你的函数,而你没有为你的类型参数给出明确的类型。

所以编译器认为它没有任何类型可以使用,并回退到 {}("empty type",通常简称为 "curly curly")T.

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

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

好吧 fn 的类型基本上是 (a: {}) => void,所以编译器计算 "alright, great, we can give a a type!" 结果是...... {} 不幸的是。


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

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

或使用类型参数:

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