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

Viewed 5502

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

1 Answers

You just have to provide an element type to useRef

const Test = () => {
    const ref = useRef<HTMLInputElement>(null);
    const rect = ref?.current?.getBoundingClientRect();
}
Related