Another day, another TypeScript challenge with useRef.

How many times per day you swear when writing React code with TypeScript?..

Today I got this:

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)

Hmmm, so my input’s current property is not compatible. What exactly does it mean? I already declared my ref like this:

const inputRef = useRef<HTMLInputElement>();

Pulling my hair off, trying all kind of HTMLBlaBlaBlaElements, all I had to do was

const inputRef = useRef<HTMLInputElement>(null);

Imagine if TypeScript would be able to actually give us proper hints. (where’s the AI that all the people keep talking about??)


Did you know that I made an in-browser image converter, where you can convert your images without uploading them anywhere? Try it out and let me know what you think. It's free.

Leave a Comment

Your email address will not be published. Required fields are marked *