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.