首页 > 解决方案 > 类型 {} 上不存在属性 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"}。

因此,此代码正在运行,但会引发打字稿错误。

请帮助我如何解决上述打字稿错误。

标签: typescriptreact-router

解决方案


似乎 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;

推荐阅读