HomeAnother day, another TypeScript challenge with useRef.

Another day, another TypeScript challenge with useRef.

Published: 11/22/2023

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??)

About Code with Node.js

This is a personal blog and reference point of a Node.js developer.

I write and explain how different Node and JavaScript aspects work, as well as research popular and cool packages, and of course fail time to time.