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

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

const ref = useRef()

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

错误:

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

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

回答

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

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


以上是TS2339:属性“getBoundingClientRect”在“从不”类型上不存在的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>