对象是来自 userReducer 的“未知”类型

时间:2021-05-27 14:58:49

标签: reactjs typescript use-reducer

我在此处声明的 Object is of type 'unknown' 状态变量的打字稿中不断收到错误 currentUser

    const initialCurrentUserState: UserInfoObj = localStorageObject["userInfo"]
    const [currentUser, dispatchCurrentUser] = useReducer(currentUserReducer, initialCurrentUserState);

    let loggedIn: boolean = currentUser?.user_id > 0;

错误发生在最后一行: screengrab showing currentUser error

当我将鼠标悬停在 initialCurrentUserState 上时,打字稿告诉我它的类型为 UserInfoObj,但是当我将鼠标悬停在代码中的任何 currentUser 上时,打字稿告诉我它的类型为 {{ 1}}。

(其他可能相关的代码:

unknown
export interface UserInfoObj {
    user_id: number;
    firebase_uid: string;
    firebase_id: string;
    email: string;
    dob: string;
    name: string;
    country: null;
    unitcm: number;
    isadmin: boolean;
}

interface Action {
  type: 'UPDATE_USER';
  payload: UserInfoObj;
}

export const currentUserReducer = (state: UserInfoObj, action: Action ) => {
  switch (action.type) {
    case 'UPDATE_USER':
      return {...action.payload}
    default:
      console.log('firing dispatch - state, action:', state, action);
      return state;
  }
} 

我想了解为什么以及如何避免此错误。

0 个答案:

没有答案