【问题标题】:cannot solve ts error: Object is possibly 'undefined'.ts(2532)无法解决 ts 错误:对象可能是“未定义”.ts(2532)
【发布时间】:2021-06-03 03:27:10
【问题描述】:

我有以下代码:

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

我在 vscode 中收到以下错误:

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

尽管我试图用 if 子句和可选的链接运算符来避免它。

从控制台我得到同样的错误:

$ 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.

还检查了这个 SO 答案:How can I solve the error 'TS2532: Object is possibly 'undefined'?

还有这篇博文:https://linguinecode.com/post/how-to-solve-typescript-possibly-undefined-value

但我似乎无法解决问题

顺便说一句,这是我的 ts 版本:

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

【问题讨论】:

  • 尝试将 null 传递给您的 useRef 钩子 - useRef(null); 看看是否有帮助。
  • 是的!请将其添加为 aswer,以便我接受它

标签: reactjs typescript


【解决方案1】:

通过将null 的初始值传递给useRef 挂钩解决了这个问题:

const queryInput = useRef(null);

【讨论】:

    猜你喜欢
    • 2020-02-21
    • 2021-08-07
    • 2019-09-16
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2021-02-03
    • 2021-06-06
    相关资源
    最近更新 更多