简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM