bobypoz
bobypoz

Reputation: 41

How to avoid Typescript Object is possibly 'null'. TS2531

I am trying to get the scroll position using the following code:

    useEffect (()=>{
    document.addEventListener("scroll", e => {
        let scrolled = document.scrollingElement.scrollTop;
        if (scrolled >= 5){
           setPos("moved")
        } else {
           setPos("top")
        }
    })
  },[])

Typescript complains about the document.scrollingElement.scrollTop saying that it is possibly null. How do I avoid this error and keep typescript happy?

Upvotes: 1

Views: 1099

Answers (3)

zhuber
zhuber

Reputation: 5534

Just do a null check

useEffect(() => {
  document.addEventListener("scroll", e => {
    if (document.scrollingElement !== null) {
      const scrolled = document.scrollingElement.scrollTop;
      if (scrolled >= 5) {
        setPos("moved")
      } else {
        setPos("top")
      }
    }
  })
}, [])

Upvotes: 0

Henry Boisdequin
Henry Boisdequin

Reputation: 465

I find a null check guard clause the best way.

useEffect (()=>{
   document.addEventListener("scroll", e => {
   let scrolled = document.scrollingElement.scrollTop;
   if (scrolled === null) {
      return;
   }
   if (scrolled >= 5){
      setPos("moved")
   } else {
      setPos("top")
    }
 })
},[])

Upvotes: 0

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19059

There are at least two ways.

  1. interrupt function if the element doesn't exist
document.addEventListener("scroll", e => {
  if (!document.scrollingElement) {
    return;
  }

  let scrolled = document.scrollingElement.scrollTop;
  ...
});
  1. Check with exclamation mark operation:
document.addEventListener("scroll", e => {
  let scrolled = document.scrollingElement!.scrollTop;
  ...
});

Upvotes: 2

Related Questions