在下面的代码片段中,尽管有一个隐式类型为 any
的参数,但 typescript 不会发出任何错误。 .
declare function constrainedHOF<T extends (...args: any[]) => any>(callback: T): T;
// x is implicitly any, but typescript does not complain
const hof = constrainedHOF(x => {
console.log(x);
});
我的猜测是问题是类型约束 T extends (...args: any[]) => any
,这让 typescript 认为它是一个显式的 any
.如何正确解决这个问题,既保持泛型类型约束为“任何类型的函数”,又让 typescript 提示隐式
any
当它在 constrainedHOF
中遇到意外未键入的回调时?在最新的稳定版 Typescript 3.9.2 中测试。
我准备了一个 Playground Link这证明了问题,包括检查问题确实来自通用约束。
最佳答案
使用 Function
怎么样?界面?
// according to your declaration, you return a function, is that correct?
declare function callbackHOF<T extends Function>(callback: T): T
// @ts-expect-error noImplicitAny
const callbackHofNonTyped = someHOF(x => {
console.log(x);
});
const callbackHofTyped = someHOF((x: number) => {
console.log(x);
});
这是一个 playground link
关于typescript - noImplicitAny 不适用于通用高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63062652/