Home > OS >  Type 'MutableRefObject<HTMLInputElement | undefined>' is not assignable to type 
Type 'MutableRefObject<HTMLInputElement | undefined>' is not assignable to type 

Time:11-03

Given this very simple component :

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 */}
    )
})

I have this error :

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)

What does this mean? How to fix this error?

CodePudding user response:

You should pass an initial value to the useRef hook. Adding | undefined is also not needed:

React.useRef<HTMLInputElement>(null)
  • Related