React Useref Property Not Exist On Type Never

2 menit baca.

Kamu pakai useRef dan TypeScript marah:

const inputRef = useRef(null);

inputRef.current.value; // Property 'value' does not exist on type 'never'

That type 'never' membingungkan. Let's fix.

Kenapa terjadi

useRef(null) meng-infer tipe sebagai MutableRefObject<null>, yang berarti current hanya bisa null. TypeScript mempersempit jadi never karena setelah di-init dengan null, TypeScript assumes ref tidak akan pernah punya nilai.

Solusinya

Opsi 1: Berikan type argument

const inputRef = useRef<HTMLInputElement>(null);
inputRef.current.value; // Work
inputRef.current.focus(); // Juga work

Opsi 2: Pakai undefined sebagai nilai awal

const inputRef = useRef<HTMLInputElement | undefined>(undefined);
inputRef.current?.value; // Aman dengan optional chaining

Opsi 3: Buat ref di dalam useEffect

const inputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
  if (inputRef.current) {
    inputRef.current.focus();
  }
}, []);

Untuk callback refs

const setInputRef = (element: HTMLInputElement) => {
  inputRef.current = element;
};

return <input ref={setInputRef} />;

TL;DR

Cuma tambahkan type argument:

const ref = useRef<HTMLInputElement>(null);

Selesai. useRef<HTMLElement>(null) kasih tau TypeScript tipe apa yang di-hold oleh ref.

Latest Posts