title: TypeScript: Issues with KeyboardEvent/Event type and addEventListener
body: <p>I've coded a React burger menu that operates properly using regular JS/JSX but not with TS/TSX.</p>
  <p><strong>The issue lies in my choice of type for the <code>keydown</code> event (as an argument for the <code>keyboardHandler</code> function), showing this error:</strong></p>
  <blockquote>
  <p>No overload matches this call.   Overload 1 of 2, '(type: &quot;keydown&quot;,
  listener: (this: Document, ev: KeyboardEvent) =&gt; any, options?:
  boolean | AddEventListenerOptions | undefined): void', gave the
  following error.
  Argument of type '(e: KeyboardEvent) =&gt; void' is not assignable to parameter of type '(this: Document, ev: KeyboardEvent) =&gt; any'.
  Types of parameters 'e' and 'ev' are incompatible.
  Type 'KeyboardEvent' is missing the following properties from type 'KeyboardEvent': locale, nativeEvent,
  isDefaultPrevented, isPropagationStopped, persist</p>
  </blockquote>
  <p>Overload 1 of 2 is linked to <code>keyboardHandler</code>'s subscription by the <code>addEventListener</code> upon component's mounting, overload 2 of 2 is linked its unsubscription upon unmounting.</p>
  <pre><code>import React, { FC, Dispatch, KeyboardEvent, useEffect } from &quot;react&quot;;
  
  export interface IBurgerMenu {
    toggled: boolean;
    navbar: boolean;
    setToggled: Dispatch&lt;React.SetStateAction&lt;boolean&gt;&gt;;
  }
  
  /* Props from Nav component */
  const BurgerMenu: FC&lt;IBurgerMenu&gt; = ({ toggled, setToggled, navbar }) =&gt; {
    useEffect(() =&gt; {
      document.addEventListener(&quot;keydown&quot;, keyboardHandler, true);
      return () =&gt; {
        document.removeEventListener(&quot;keydown&quot;, keyboardHandler, true);
      };
    });
  
    // On/Off menu button
    const toggleMenu = () =&gt; {
      setToggled(!toggled);
    };
  
    // Closes menu if escape key pressed
    const keyboardHandler = (e: KeyboardEvent) =&gt; {
      if (e.key === &quot;Escape&quot;) {
        setToggled(false);
      }
    };
  
    return (
     // Irrelevant HTML
    );
  };
  
  export default BurgerMenu;
  
  </code></pre>
  <p>As suggested here: <a href="https://stackoverflow.com/questions/58162113/react-typescript-issue-on-addevenlistener">react typescript issue on addEvenListener</a> &amp; <a href="https://stackoverflow.com/questions/59673494/no-overload-matches-this-call-for-removeeventlistener-and-addeventlistener">&quot;No overload matches this call&quot; for removeEventListener and addEventListener</a> the following has been attempted:</p>
  <ul>
  <li>Using <code>Event</code> instead of <code>KeyboardEvent</code>. However, the Property <code>'key'</code> does not exist on type <code>'Event'</code>. <code>e.key</code> therefore becomes an issue.</li>
  <li>Using <code>any</code> as a type, which defeats the purpose of TypeScript.</li>
  </ul>
  <p>Thanks in advance for your help.</p>