Home > Net >  How to type a variable with useRef with TypeScript
How to type a variable with useRef with TypeScript

Time:01-02

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 '{}'

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

CodePudding user response:

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

  • Related