I have a question while studying for TS.
I created a useScroll custom hook.
When defining the type in this hook,
what is the difference between using the type and using ?
export default function useScroll<T extends HTMLElement>(
handleScrollDown: () => void,
handleScrollUp: () => void,
): RefObject<T> {
const ref = useRef<T>(null);
export default function useScroll<HTMLElement>(
handleScrollDown: () => void,
handleScrollUp: () => void,
isUsable = true,
): RefObject<HTMLElement> {
const ref = useRef<HTMLElement>(null);
useEffect(() => {
const element = ref.current;
if (!isUsable || !element) return;
const handleWheel = (event: WheelEvent) => {
if (event.deltaY < 0) {
handleScrollUp();
} else if (event.deltaY > 0) {
handleScrollDown();
}
};
element.addEventListener("wheel", handleWheel);
return () => {
element.removeEventListener("wheel", handleWheel);
};
}, [handleScrollDown, handleScrollUp, isUsable]);
return ref;
}
and in the latter method,
“element.addEventListener(“wheel”, handleWheel)” causes this type error.
‘addEventListener’ does not exist on Type ‘NonNullable’
Why does this happen??
I looked up a book about generic types, but I didn’t understand it well, so I hope I can understand it easily.
jae6269 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.