Mengatasi useRef "Property does not exist on type 'never'"

Terbit pada · Diperbarui pada
3 menit baca.
Tags: JavaScriptTypeScriptReact

Kamu memakai useRef, lalu TypeScript menampilkan error:

const inputRef = useRef(null);

if (inputRef.current) {
  inputRef.current.value; // Property 'value' does not exist on type 'never'
}

Pesan type 'never' ini membingungkan. Begini cara memperbaikinya.

Penyebabnya

useRef(null) di-infer sebagai RefObject<null> (MutableRefObject<null> sebelum React 19), jadi current hanya bisa berisi null. Pengecekan if (inputRef.current) menyingkirkan null, dan tidak ada tipe lain yang tersisa, sehingga TypeScript mempersempit current jadi never. Kalau pengecekan itu dihapus, error-nya berubah jadi 'inputRef.current' is possibly 'null'.

Solusinya

Opsi 1: Tulis type argument

const inputRef = useRef<HTMLInputElement>(null);
inputRef.current?.value; // Works
inputRef.current?.focus(); // Also works

Sekarang current bertipe HTMLInputElement | null, jadi ?. atau pengecekan if tetap diperlukan. Isinya null sampai React memasang elemennya.

Jangan mengganti null dengan undefined. useRef<HTMLInputElement | undefined>(undefined) langsung error begitu dipasang ke <input ref={inputRef} />, karena prop ref di React meminta HTMLInputElement | null.

Opsi 2: Baca ref di dalam useEffect

const inputRef = useRef<HTMLInputElement>(null);

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

Kalau pakai callback ref

const inputRef = useRef<HTMLInputElement | null>(null);

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

return <input ref={setInputRef} />;

Saat elemen di-unmount, React memanggil callback ini dengan null, jadi tipe parameternya harus HTMLInputElement | null.

Parsing error di file .jsx

useRef<HTMLInputElement>(null) adalah sintaks TypeScript. Di file .js atau .jsx, ESLint dan Babel menganggap <HTMLInputElement> sebagai JSX, lalu melaporkan parsing error. Ubah nama file jadi .tsx, atau tetap di JavaScript dan tulis tipenya lewat komentar JSDoc:

/** @type {import('react').RefObject<HTMLInputElement | null>} */
const inputRef = useRef(null);

Kalau checkJs aktif, TypeScript membaca komentar itu dan inputRef.current mendapat tipe yang sama seperti di versi .tsx.

TL;DR

Tulis type argument-nya:

const ref = useRef<HTMLInputElement>(null);

Dengan useRef<HTMLElement>(null), TypeScript jadi tahu tipe elemen yang akan disimpan ref.