TS2339:属性“getBoundingClientRect”在“从不”类型上不存在

Atr*_*rag 4 typescript reactjs

我知道可选链接应该足够了,但我在这里尝试满足 TypeScript 有点过火:

const ref = useRef()

    if (ref !== undefined) {
        if(ref.hasOwnProperty('current')) {
            if (ref.current !== undefined &&  ref.current !== null)
             console.log(ref?.current?.getBoundingClientRect())
        }
    }
Run Code Online (Sandbox Code Playgroud)

错误:

TS2339: Property 'getBoundingClientRect' does not exist on type 'never'.
Run Code Online (Sandbox Code Playgroud)

我想念我不打字的日子......除了 @ts-ignore

小智 6

你只需要提供一个元素类型来 useRef

const Test = () => {
    const ref = useRef<HTMLInputElement>(null);
    const rect = ref?.current?.getBoundingClientRect();
}
Run Code Online (Sandbox Code Playgroud)