Typescript React useCallback eslint force typed arguments

Viewed 371

I'm trying to force correct typings on all useCallbacks in react with typescript and eslint.
By default the arguments defined in useCallback are of type any.

// @types/react
function useCallback<T extends (...args: any[]) => any>(callback: T, deps: DependencyList): T;

What this means is that both typescript and typescript-eslint's no-explicit-any rule doesn't pick this up (as it's defined as any).

So if I write the following code:

const callback = React.useCallback((value) => {
  ...
}, []);

I would like either typescript or eslint to throw me an error as value is any here.

Is there an eslint plugin that can handle this for me? Or am I missing something obvious here?

2 Answers

You can type the function manually, I don't know about any automations that could help you here:

const callback = React.useCallback<(value: string)=>void>((value)=>{
  // value should be typed as string now
}, []);

As of now, I didn't find a rule which would prohibit the usage of any type. To mitigate the problem, we ended up making the rules around usage of any as strict as possible with this set of rules:

// eslint setinngs rules:
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-unsafe-call": "error",
"@typescript-eslint/no-unsafe-member-access": "error",
"@typescript-eslint/no-unsafe-argument": "error",
"@typescript-eslint/no-unsafe-assignment": "error",
Related