类型 'MutableRefObject<HTMLInputElement | undefined>' 不可分配给类型 'LegacyRef<HTMLInputElement> | 不明确的'

Yan*_*hon 91 typescript reactjs

鉴于这个非常简单的组件:

const InputElement => React.forwardRef((props:any, ref) => {
    const handleRef = React.useRef<HTMLInputElement|undefined>()
    React.useImperativeHandle(ref, () => ({
        setChecked(checked:boolean) {
            if (handleRef.current) {
                handleRef.current.checked = checked;
            }
        }
    }), []);
    return (
        <input ref={ handleRef } type="checkbox" />  {/* <-- error here */}
    )
})
Run Code Online (Sandbox Code Playgroud)

我有这个错误:

Type 'MutableRefObject<HTMLInputElement | undefined>' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
  Type 'MutableRefObject<HTMLInputElement | undefined>' is not assignable to type 'RefObject<HTMLInputElement>'.
    Types of property 'current' are incompatible.
      Type 'HTMLInputElement | undefined' is not assignable to type 'HTMLInputElement | null'.
        Type 'undefined' is not assignable to type 'HTMLInputElement | null'.ts(2322)
Run Code Online (Sandbox Code Playgroud)

这是什么意思?如何修复这个错误?

Env*_*nve 246

要修复该错误,您应该将null初始值传递给useRef挂钩。您不需要添加| undefined

React.useRef<HTMLInputElement>(null)
Run Code Online (Sandbox Code Playgroud)

错误消息表明该refprop 需要一个 ref HTMLInputElement | null,但是如果您没有向useRef钩子传递任何内容,则它的计算结果为HTMLInputElement | undefined,这就是收到错误消息的原因:

Type 'undefined' is not assignable to type 'HTMLInputElement | null'
Run Code Online (Sandbox Code Playgroud)

为了更好地理解发生的情况,以下是如何使用简单的函数重现相同的错误:

// This function expects a ref similar to how an element like <input> does
const someFunction = (ref: RefObject<HTMLElement | null>) => {};

// the type of `ref` below will be RefObject<HTMLElement | undefined>
const ref = useRef<HTMLElement>();

// throws `Type 'undefined' is not assignable to type 'HTMLElement | null'`
someFunction(ref);
Run Code Online (Sandbox Code Playgroud)

只是如何在 prop 中得到错误ref,您将在最后一行的函数调用中得到相同的错误。如果传递nulluseRef钩子,则 的类型ref将变为RefObject<HTMLElement | null>,它与函数期望的类型兼容,因此不会引发错误。

  • 但为什么我会得到这样一个误导性的错误呢? (16认同)