react typescript 'current' is not present in type 'never'

Viewed 967

I am using react and typescript. I wanted to get the height of the div tag, so I used useRef. However, I get a ts error in current.

Property 'current' is not present in type 'never'. ts(2339)
    const ref = useRef<HTMLDivElement>(null);

    useEffect(() => {
      if (ref != null || ref.current != null) {
        setHeight(ref.current.clientHeight);
      }
    }, [user]);

2 Answers

Note that the errors are gone when you change the code to be:

if (ref !== null && ref.current != null) {
    setHeight(ref.current.clientHeight);
}

I changed the || to &&.

This means that your condition ref.current != null will "NEVER" be true if ref != null is true

I can see in your logic, you are trying to check if ref.current is not null before reference to ref.current.clientHeight

So the correct condition should be:

useEffect(() => {
  if (ref !== null && ref.current !== null) {
    setHeight(ref.current.clientHeight);
  }
}, [user]);

The || condition runs from left to right, if you want to keep using your condition then change the order to:

useEffect(() => {
  if (ref.current !== null || ref !== null) {
    setHeight(ref.current.clientHeight);
  }
}, [user]);
Related