Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to type a variable with useRef with TypeScript

I use useRef() to deal with errors of a phone number from an input. I do it like this:

const errorPhoneDiv: MutableRefObject<{}> = useRef("");

A bit later in the code, I use errorPhoneDiv.current.innerText to set the written phone number, but TS tells me :

Property ‘innerText’ does not exist on type ‘{}’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What type should I pass to MutableRefObject to accept the useRef object?

>Solution :

You could use HTMLInputElement if it’s an input, HTMLDivElement if it’s a div, etc. You also need an initial value, which could be null, in which case you need a null check before accessing innerHTML:

const errorPhoneDiv = useRef<HTMLInputElement | null>(null);
console.log(errorPhoneDiv.current?.innerHTML);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading