Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ref in Typescript Nextjs

I learning typescript in react but got an warning

import {useref} from 'react'

export default function test(){
   cons tmp = useRef()
   const data = tmp.current?.value
   return (
      <div>
        <input type ="text" ref={tmp}/>
      </div>

) }

but I got warning like this

Property 'value' does not exist on type 'never'.ts(2339)

can someone help me to fix it ?

and one more question, what Type Annotation of props.example() ?

like image 367
just test Avatar asked Sep 03 '26 19:09

just test


1 Answers

You need to provide a type to useRef so it know what to expect. You also need to initialize it as null.

const tmp = useRef<HTMLInputElement>(null)

Then everything works as you expect.

Working example on Typescript playground

like image 116
Alex Wayne Avatar answered Sep 06 '26 09:09

Alex Wayne