Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 750
Atrag Avatar asked Feb 15 '21 22:02

Atrag


People also ask

Does the property'name'exist on type'never'in typescript?

TS2339: Property 'name' does not exist on type 'never'. Have no idea how to solve this. Seems that typescript doesn't understand at all that variable could be initialized from callback function.

Does not exist on type'MyClass'property?

When compiled/transpiled through TypeScript it generates error TS2339: Property 'myclassvar' does not exist on type 'MyClass'. If the above code snippet is valid ES6 then TypeScript should not generate the error. The generated javascript it valid. It's just that the error scares the developers trying to use ES6 without typings.

What is getting error ts2339?

Getting error TS2339: Property does not exist on type for a valid ES6 class #6373. Getting error TS2339: Property does not exist on type for a valid ES6 class. #6373.

What is the difference between ts2454 and ts2339?

Here is a small example: TS2454: Variable 'user' is used before being assigned. TS2339: Property 'name' does not exist on type 'never'. Have no idea how to solve this. Seems that typescript doesn't understand at all that variable could be initialized from callback function.


1 Answers

You just have to provide an element type to useRef

const Test = () => {
    const ref = useRef<HTMLInputElement>(null);
    const rect = ref?.current?.getBoundingClientRect();
}
like image 170
user2369284 Avatar answered Oct 16 '22 12:10

user2369284