Search code examples
reactjstypescripteslinttypescript-eslint

Is there an eslint rule to enforce types for useState()?


I would like to make sure that all our team members properly type their hooks.

const [users, setUsers] = useState<User>([]); // --> should work
const [users, setUsers] = useState([]); // --> should throw a linting error

So far I couldn't find such a rule. How could I do it myself if there is no existing plugin?


Solution

  • eslint-plugin-require-explicit-generics looks like what you are looking for.

    https://www.npmjs.com/package/eslint-plugin-require-explicit-generics

    to the options you pass name of the functions that you want the generic type to be enforced (eg. useState or React.useState)