using ref in typescript nextjs

Viewed 1684

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() ?

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

Related