opensas
opensas

Reputation: 63415

cannot solve ts error: Object is possibly 'undefined'.ts(2532)

I have the following code:

  const queryInput = useRef()
  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (queryInput && queryInput.current) {
      console.log(`queryInput.current.value`, queryInput?.current?.value ?? null)
    }
  }
  return (
...

And I'm getting the following error in vscode:

(property) MutableRefObject<undefined>.current: undefined
Object is possibly 'undefined'.ts(2532)

Even though I tried to avoid it with the if clause and the optional chaining operator.

From the console I get the same error:

$ npx tsc
pages/_app.tsx:14:47 - error TS2532: Object is possibly 'undefined'.

14       console.log(`queryInput.current.value`, queryInput?.current?.value ?? null)
                                                 ~~~~~~~~~~~~~~~~~~~


Found 1 error.

Also checked this SO answer: How can I solve the error 'TS2532: Object is possibly 'undefined'?

and this blog post: https://linguinecode.com/post/how-to-solve-typescript-possibly-undefined-value

but I can't seem to solve the issue

BTW, this is my ts version:

  "devDependencies": {
    "@types/node": "^14.14.31",
    "@types/react": "^17.0.2",
    "typescript": "^4.2.2"

Upvotes: 1

Views: 2225

Answers (1)

mtbno
mtbno

Reputation: 600

The problem was fixed by passing initial value of null to the useRef hook:

const queryInput = useRef(null);

Upvotes: 3

Related Questions