I'm still a bit new to Typescript and my goal is to create a custom React.useRef hook in Typescript that returns a ref. I would like this ref to be typed for any HTML element and not just buttons only. I'm running into issues of typing this custom hook properly.
Here's my hook:
type CustomRefHook = (dependencies?: string | boolean | number[]) => React.MutableRefObject<HTMLButtonElement | null>;
const useCustomRefHook: CustomRefHook = (...dependencies) => {
const ref = React.useRef<HTMLButtonElement | null>(null);
useEffect(() => {
// ... do stuff
}, dependencies)
return ref;
}
For now, the majority of my use cases for this hook would be for buttons but I would like to eventually expand this to any sort of HTML element. I've tried using HTMLElement instead of HTMLButtonElement , however I get a type error of:
Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'string | ((instance: HTMLButtonElement | null) => void) | RefObject<HTMLButtonElement> | null | undefined'.
Type 'MutableRefObject<HTMLElement | null>' is not assignable to type 'RefObject<HTMLButtonElement>'.
Types of property 'current' are incompatible.
Type 'HTMLElement | null' is not assignable to type 'HTMLButtonElement | null'.
whenever I try to attach this ref to a button. Using HTMLButtonElement quiets the Typescript errors, but again I'd like this hook to be able to handle any type of HTML element.
type CustomRefHook = <T>(dependencies?: string | boolean | number[]) => React.MutableRefObject<T>;