React+TypeScript中reducer变量访问报错?提示loading不存在于object类型
问题原因分析
报错Property 'loading' does not exist on type 'object'的核心原因是TypeScript的类型约束不明确:
- 你给reducer函数的返回值显式标注了
object类型,这个类型在TS里是最宽泛的通用对象类型,不包含任何具体属性的定义。TypeScript无法从这个类型中推断出loading属性的存在,所以访问itemList.loading时会触发报错。 - 虽然你定义了带有
loading属性的initialState,但reducer的返回类型object覆盖了TS对初始状态的自动类型推断,导致itemList的类型被限定为无具体属性的object,而非包含loading的具体对象。
修复方案
推荐定义明确的状态类型来解决这个问题,代码示例如下:
import { useReducer } from "react"; // 定义状态的具体类型接口 interface AppState { loading: boolean; // 后续添加的状态属性都可以在这里声明 } // 使用定义好的类型约束reducer的参数和返回值 const reducer = (state: AppState, action: any): AppState => { const result = { ...state }; // ...你的业务逻辑 return result; } // 用接口约束初始状态 const initialState: AppState = { loading: true }; export default function TestWebRTC() { const [itemList, updateItemList] = useReducer(reducer, initialState); return ( <div> {itemList.loading} </div> ) }
也可以让TypeScript自动推断类型,去掉reducer的返回类型标注,同时用typeof initialState约束state参数:
const reducer = (state: typeof initialState, action: any) => { const result = { ...state }; // ...你的业务逻辑 return result; }
内容的提问来源于stack exchange,提问作者The KNVB
相关产品推荐
相关产品推荐

