Reputation: 63415
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