4

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();
+  }; 

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.