typescript - 类型 {} 上不存在属性 ID
问题描述
const state = history.location.state;
const id = state?.id;
以下是打字稿错误:
Property 'id' does not exist on type '{}'. TS2339
我从 history.location.state 获取 id 值,即从 react-router 我将 id 道具作为状态发送到 history.push("pathname",{id:"some value"}。
因此,此代码正在运行,但会引发打字稿错误。
请帮助我如何解决上述打字稿错误。
解决方案
似乎 TypeScript 编译器不知道history.location.state
. 你可以尝试为 React 安装类型:
npm install --save-dev @types/react @types/react-dom @types/react-router-dom
或者,要绕过错误,您可以强制state
键入any
:
const state = history.location.state;
const id = (state as any)?.id;
推荐阅读
- angularjs - 删除菜单中的初始背景颜色第一个 md 按钮
- mysql - Mysql count case with join
- python - 打印模式的 Python 递归函数
- java - 限制 PLAIN_MESSAGE JOptionPane 中输入文本的大小
- java - Spring Security JWT - 400 错误请求:“无效授权”“错误凭据”
- angular - 无法解析“@angular/router/src/utils/collection”
- npm - 是否可以使用 webpack 分别导入捆绑的 webpack 和库?
- beacon - 我如何搜索信标
- javascript - Javascript Recussion 错误 - RangeError:超出最大调用堆栈大小
- reactjs - 我可以在 reactjs 中使用 Tensorflow 吗?(不是反应原生的)