TypeScript连接Redux类组件到reducer时报错:DefaultRootState不存在unit属性
解决Redux+TS报错
Property 'unit' does not exist on type 'DefaultRootState' 这个报错的核心原因是TypeScript默认使用React Redux内置的DefaultRootState类型作为store根状态的类型,该默认类型没有包含你自定义的unit等reducer字段。你已经定义了RootState类型,只需要让TS识别这个自定义类型即可,有两种常见解决方案:
- 方案1:单文件临时修复
直接给mapState的state参数标注你自定义的RootState类型即可,修改代码如下:
// 替换为你项目中rootReducer的实际路径 import { RootState } from './store/rootReducer'; export default connect( (state: RootState) => ({ unit: state.unit }), { fetchRegisterAll } )(TabNavUnits);
该方案适合只需要修复单个组件报错的场景。
- 方案2:全局类型声明,一劳永逸解决所有同类报错
在项目src目录下新建全局类型声明文件(例如src/redux.d.ts),写入以下内容:
import 'react-redux'; // 替换为你项目中rootReducer的实际路径 import { RootState } from './store/rootReducer'; declare module 'react-redux' { interface DefaultRootState extends RootState {} }
声明完成后如果没有立即生效,可以重启IDE的TS服务(VSCode中按Ctrl+Shift+P,选择「TypeScript: Restart TS Server」即可)。配置完成后所有组件使用connect或者useSelector时,默认都会使用你定义的根状态类型,无需再单独标注state类型,不会再出现同类报错。
内容的提问来源于stack exchange,提问作者xyz83242
相关产品推荐
相关产品推荐

