【问题标题】:noImplicitAny does not work on generic higher order functionnoImplicitAny 不适用于通用高阶函数
【发布时间】:2020-07-24 10:09:50
【问题描述】:

在下面的 sn-p 中,尽管有一个参数隐式键入为 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[]) =&gt; any,这使得打字稿认为它是一个显式的any

如何正确解决这个问题,既保持泛型类型约束为“任何类型的函数”,又让打字稿在遇到constrainedHOF 内的意外无类型回调时抱怨隐式any

在最新的稳定版 Typescript 3.9.2 中测试。

我准备了一个 Playground Link 来演示问题,包括检查问题是否真的与通用约束有关。

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    使用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

    【讨论】:

    • 谢谢!真的行。我只记得我在某处看到不推荐使用 Function 类型,但我现在无法找到可靠的来源。它也不会涵盖所有情况,例如&lt;T extends (foo: number, ...args: any[]) =&gt; any&gt;,但对我来说就足够了:)
    • 我发现函数的第一个问题。 TS 无论如何都无法与大多数 HOF 中需要的函数类型一起工作。 Playground Link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多