Search code examples
reactjstypescripteslintprop

How to properly use a change function on react button and not have any unused variables


I'm looking to have a basic button in which I can pass a type to a function on click. However, I would like to do it without having the event within the function since I do get a linting error — event is definied but never used.

const Test: React.FC = () => {
  const [state, setState] = useState(null);
  const handleClick = (type: string) => (event: object) => {
    switch (type) {
      case 'CASE_1':
        doSomething(state);
        break;
      default:
        return;
    }
  };

  return (
    <button onClick={handleClick('CASE_1')}>CLICK ME</button>
  )
}

Solution

  • To fix this in regards to TypeScripts built-in linter:

    1. Prefix the unused parameter's name with an underscore: (_event: object) => {

    From the TypeScript docs:

    Parameters declaration with names starting with _ are exempt from the unused parameter checking.

    1. You can also disable unused parameter warnings globally in your TypeScript configuration with the noUnusedParameters flag.

    In general, any linter should be silenced by just omitting the argument entirely: () => {...
    If this function was called from TypeScript with an argument, the compiler (and possibly other linters) would then complain about the extraneous argument at the call site.
    But because it is only called by React, this doesn't happen.