reactjstypescriptreact-forwardref

Getting "Type 'null' is not assignable to type 'HTMLInputElement'" while using "useImperativeHandle"


I'm trying to build a component which accepts a forwarded ref but also maintains and uses an internal ref (such that both component and caller can access the HTML reference).

import { forwardRef, useImperativeHandle, useRef } from "react";

type FancyInputProps = {};

export const FancyInput = forwardRef<HTMLInputElement | null, FancyInputProps>(
  function FancyInput({}, forwardedRef) {
    const inputRef = useRef<HTMLInputElement | null>(null);
    useImperativeHandle(forwardedRef, () => inputRef.current);

    return <input ref={inputRef} type="text" />;
  }
);

My issue here is that TypeScript is complaining about mismatching between the types (see img below). TS is saying that inputRef.current is can be null (of course...) and that's not assignable to forwardedRef which, although I explicitly set it to allow null is being seen as HTMLInputElement.

What am I missing here? How can I change and type my component so that I can use the same ref inside and outside of the component and also have valid TS types?

enter image description here


Solution

  • Perhaps a bit verbose, but, you can inform TypeScript by providing types to useImperativeHandle generics:

    useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
        forwardedRef, () => ref.current
    );