Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript error Property 'clientHeight, scrollHeight, scrollTop' does not exist on type 'HTMLDivElement | null',

I have used useRef hook for my scroll function, I have set HTMLDivElement type but I am getting Property 'clientHeight, scrollHeight, scrollTop' does not exist on type 'HTMLDivElement | null',

If I hover on useRef it says (alias) useRef<HTMLDivElement>(initialValue: HTMLDivElement | null): RefObject<HTMLDivElement> (+2 overloads) import useRef

  const scrollRef = useRef<HTMLDivElement>(null);
  const getActivityFeedOnScroll = () => {
    const {scrollTop, scrollHeight, clientHeight} = scrollRef?.current;
    scrollTop + clientHeight === scrollHeight && fetchNextPage();
  };

If I do like it this way, the type is not giving me the error, but I want to replace the if conditions with null guard, to make the code cleaner.

 +  const getActivityFeedOnScroll = () => {
+    if (!scrollRef.current) return;
+    const {scrollTop, scrollHeight, clientHeight} = scrollRef.current;
+    if (scrollTop + clientHeight === scrollHeight) fetchNextPage();
+  }; 
like image 297
Anik Ahmed fathe Avatar asked Oct 19 '25 12:10

Anik Ahmed fathe


1 Answers

To the best of my knowledge, you simply cannot do this.

Think about it, in your first code block, you say { someStuff } = scrollRef?.current; If scrollRef is undefined or nullish it doesn't try to access current, that would throw something along the lines of "property current does not exist on type undefined". Instead, scrollRef?.current is just then null, and { someStuff } therefore makes no sense.

If the typescript language did allow you to do this, you would have to check to make sure if someStuff is not nullish like this.

  const scrollRef = useRef<HTMLDivElement>(null);
  const getActivityFeedOnScroll = () => {
    const {scrollTop, scrollHeight, clientHeight} = scrollRef?.current;
    if (scrollTop && clientHeight && scrollHeight)
        scrollTop + clientHeight === scrollHeight && fetchNextPage();
  };

This is messier than your second case (which is the right way to do things).

To summarize, if your first case didn't give you an error on scrollRef?.current, it would instead give it to you on the next line, where you go to use the properties of scrollRef?.current.

Your code isn't messier, it doesn't have more "boilerplate", it's just more explicit, which is a good thing. You are explicitly telling your code what to do when scrollRef.current is nullish.

like image 150
BenMcLean981 Avatar answered Oct 21 '25 02:10

BenMcLean981