How to Fix "Property 'x' does not exist on type 'never'" TypeScript Error When Using React useRef()?

Why Does This Happen?

When attempting to access the current property of a React reference object in a null-safe manner (e.g., by using optional chaining), you might encounter the "Property '...' does not exist on type 'never'" error as shown in the example below:

const Foo = () => {
  const inputElem = useRef(null);

  useEffect(() => {
    // error: Property 'value' does not exist on type 'never'.
    console.log(inputElem?.current?.value);
  }, []);

  return (
    <input type="text" ref={inputElem} defaultValue="foobar" />
  );
};

This error occurs because TypeScript cannot infer the type of the reference object's current property unless you explicitly specify the type when using the useRef() hook.

How to Fix the Issue?

To fix this issue, you should specify the correct type when calling useRef() using the generic parameter. The specified type should correspond to the type of the element for which you intend to maintain a reference. For instance, when creating a reference to an HTML <input> element, you should specify the type as HTMLInputElement:

const Foo = () => {
  const inputElem = useRef<HTMLInputElement>(null);

  useEffect(() => {
    console.log(inputElem?.current?.value);
  }, []);

  return (
    <input type="text" ref={inputElem} defaultValue="foobar" />
  );
};

By supplying the appropriate type, TypeScript can determine the type of the current property, effectively preventing the "Property '...' does not exist on type 'never'" error.

For a better understanding of how this works, you can refer to the useRef() type definition, which is as follows:

function useRef<T>(initialValue: T): MutableRefObject<T>

The return type of useRef() is a "MutableRefObject", which is defined as:

interface MutableRefObject<T> {
  current: T;
}

These type definitions illustrate that specifying a type using the useRef() generic parameter ensures the correct type for the current property of the reference object.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.