'Typescript React useCallback eslint force typed arguments
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?
Solution 1:[1]
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
}, []);
Solution 2:[2]
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",
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Taxel |
| Solution 2 | Vladyslav Zavalykhatko |
