What typescript type do I use with useRef() hook when setting current manually? : <p>How can I use a React ref as a mutable instance, with Typescript? The current property appears to be typed as read-only.</p>

<p>I am using React + Typescript to develop a library that interacts with input fields that are NOT rendered by React. I want to capture a reference to the HTML element and then bind React events to it. </p>

<pre><code>  const inputRef = useRef&lt;HTMLInputElement&gt;();
  const { elementId, handler } = props;

  // Bind change handler on mount/ unmount
  useEffect(() =&gt; {
    inputRef.current = document.getElementById(elementId);
    if (inputRef.current === null) {
      throw new Exception(`Input with ID attribute ${elementId} not found`);
    }
    handler(inputRef.current.value);

    const callback = debounce((e) =&gt; {
      eventHandler(e, handler);
    }, 200);

    inputRef.current.addEventListener('keypress', callback, true);

    return () =&gt; {
      inputRef.current.removeEventListener('keypress', callback, true);
    };
  });
</code></pre>

<p>It generates compiler errors: <code>semantic error TS2540: Cannot assign to 'current' because it is a read-only property.</code></p>

<p>I also tried <code>const inputRef = useRef&lt;{ current: HTMLInputElement }&gt;();</code> This lead to this compiler error:</p>

<pre><code>Type 'HTMLElement | null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.

  Type 'null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.
</code></pre>
