TypeScript提示useReducer返回currentUser为unknown类型错误如何解决
错误原因
useReducer泛型推断失败:TypeScript在未显式声明useReducer泛型的场景下,若reducer定义在外部文件、初始值来源存在隐式类型转换,就无法自动推导返回的state类型,默认将其标记为unknown,这是你遇到报错的直接原因。- 初始值类型不安全:你从localStorage读取
userInfo时仅做了顶层类型标注,没有做实际的结构校验和兜底,虽然不是当前报错的直接诱因,但也存在类型隐患。
修复方案
- 显式给
useReducer传入泛型参数,绑定state和action的类型,直接修改对应代码行即可:
// 泛型第一位指定state类型,第二位指定action类型 const [currentUser, dispatchCurrentUser] = useReducer<UserInfoObj, Action>(currentUserReducer, initialCurrentUserState);
修改后currentUser的类型会被正确识别为UserInfoObj,最后一行的currentUser?.user_id报错就会消失。
- 补全localStorage取值的类型校验和兜底,避免后续运行时出现结构缺失的问题:
// 解析localStorage存储的用户信息,为空时返回默认初始值 const rawUserInfo = localStorage.getItem('userInfo'); const initialCurrentUserState: UserInfoObj = rawUserInfo ? (JSON.parse(rawUserInfo) as UserInfoObj) : { user_id: 0, firebase_uid: '', firebase_id: '', email: '', dob: '', name: '', country: null, unitcm: 0, isadmin: false };
- 可选优化:给reducer添加显式返回类型标注,进一步提升类型可靠性:
export const currentUserReducer = (state: UserInfoObj, action: Action): UserInfoObj => { switch (action.type) { case 'UPDATE_USER': return {...action.payload} default: console.log('firing dispatch - state, action:', state, action); return state; } }
内容的提问来源于stack exchange,提问作者JimmyTheCode
相关产品推荐
相关产品推荐

