Yokiijay
Yokiijay

Reputation: 821

typescript - Question about React typescript useRef

The goal is to make a reusable hook that effects on DOM.

Example Code:

import { useEffect, useRef } from 'react';

function useFocus() {
  const domRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    domRef.current?.focus()
  }, []);

  return {
    domRef
  };
}

const App = () => {
  const { domRef } = useFocus();

  return (
    <div>
      <input type='text' ref={domRef} />
    </div>
  );
};

export default App;

Error occur:

TypeScript error in /Users/yoki/Code/Demos/use-ref-demo/src/App.tsx(20,26):
Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
  Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'RefObject<HTMLInputElement>'.
    Types of property 'current' are incompatible.
      Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.
        Type 'HTMLElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 49 more.  TS2322

    18 |   return (
    19 |     <div>
  > 20 |       <input type='text' ref={domRef} />
       |                          ^
    21 |     </div>
    22 |   );
    23 | }; 

Question: How can I give the correct type for useRef<...>() ?

The right thinking is to give the type that any type which exntends from HTMLElememnt, instead of any or assertion, please help.

The dom is not limited to input, it can be div or input or span etc, so HTMLInputElement type is not good for this case.

Upvotes: 3

Views: 1977

Answers (1)

Denis Malykhin
Denis Malykhin

Reputation: 347

Take a closer look at the error message: Type 'HTMLElement | null' is not assignable to type 'HTMLInputElement | null'.. The correct type, according to the message is HTMLInputElement | null. Also, it make sense to change useFocus a bit:

useEffect(() => {
    domRef.current?.focus()
  }, [domRef]);

Upvotes: 0

Related Questions