17

I understand optional chaining should be enough but I have gone a bit overboard here to try satisfy TypeScript:

const ref = useRef()

    if (ref !== undefined) {
        if(ref.hasOwnProperty('current')) {
            if (ref.current !== undefined &&  ref.current !== null)
             console.log(ref?.current?.getBoundingClientRect())
        }
    }

Error:

TS2339: Property 'getBoundingClientRect' does not exist on type 'never'.

I miss my non-typing days... Any solution other than @ts-ignore

Atrag
  • 653
  • 2
  • 8
  • 29
  • `ref` will always be an object, though `current` will be undefined by default. You need to use it, either within the rendering process or manually put something yourself in it. – Emile Bergeron Feb 15 '21 at 22:35
  • Does this answer your question? [React Hooks - How to target an element child (with useRef) with a variable declaration outside of useEffect?](https://stackoverflow.com/questions/60503263/react-hooks-how-to-target-an-element-child-with-useref-with-a-variable-decla) – Emile Bergeron Feb 15 '21 at 22:36
  • See also: [What typescript type do I use with useRef() hook when setting current manually?](https://stackoverflow.com/q/58017215/1218980) – Emile Bergeron Feb 15 '21 at 22:38
  • Specifically, in your case: [How to use React useRef with TypeScript](https://linguinecode.com/post/how-to-use-react-useref-with-typescript) – Emile Bergeron Feb 15 '21 at 22:42

1 Answers1

36

You just have to provide an element type to useRef

const Test = () => {
    const ref = useRef<HTMLInputElement>(null);
    const rect = ref?.current?.getBoundingClientRect();
}
user2369284
  • 549
  • 6
  • 8