history模块无LocationState导出成员的TypeScript报错求助
解决history v5导入LocationState类型报错问题
问题原因
history v5重构了类型系统,不再单独导出LocationState类型;同时你使用的react-scripts@2.1.3版本过旧,对新包的类型支持存在兼容问题。
解决方案
方案1:从react-router-dom导入类型(推荐)
你已安装react-router-dom@6.x,它封装了history的核心功能及对应类型,直接从这里导入即可:
import { History, LocationState } from "react-router-dom";
方案2:手动定义LocationState类型(若需直接使用history包)
如果必须依赖history包的类型,可以通过Location接口的属性推导:
import { Location } from "history"; // 推导默认LocationState类型 type LocationState = Location['state']; // 若需自定义状态,可结合History泛型使用 type MyCustomState = { /* 你的状态结构 */ }; import { History } from "history"; type CustomHistory = History<MyCustomState>;
方案3:升级react-scripts版本
react-scripts@2.1.3是多年前的旧版本,配套的TypeScript版本过低,无法正确解析新包的类型定义。执行以下命令升级到最新稳定版:
npm install react-scripts@latest # 或使用yarn yarn add react-scripts@latest
升级后重启项目,类型报错大概率会消失。
内容的提问来源于stack exchange,提问作者Dixg
相关产品推荐
相关产品推荐

