6

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 Answer 1

12

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I have 1 more question, if I have a props example props.example(), what type annotation ?
Typically I defined react props like so: tsplay.dev/m3Akbw but if you need more help than that, please make a new question where you can explain your situation in full and get the proper help that you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.