noImplicitAny does not work on generic higher order function

Viewed 181

In the snippet below, typescript does not emit any error although there is an argument implicitly typed as any.

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

My guess is that the problem is the type constraint T extends (...args: any[]) => any, which makes typescript think that it is an explicit any.

How to solve this properly, both keeping the generic type constraint to be "function of any type" and making typescript complain about implicit any when it encounters an accidentally untyped callback inside the constrainedHOF?

Tested in latest stable Typescript 3.9.2.

I prepared a Playground Link that demonstrates the problem including a check that the problem really comes with the generic constraint.

1 Answers

What about using the Function interface?

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

here's a playground link

Related