开发者问题收集

TS2339 Typescript 错误但不确定为什么...类型上不存在属性

2020-07-17
1951

我对 Typescript 还比较陌生,目前正在构建一个包含 Redux 并使用 Typescript 的 React 应用。

Typescript 在我的 Reducer 中给了我以下错误;

ERROR in /Users/<REDACTED>/web/src/redux/reducers/steppedViews.ts
./src/redux/reducers/steppedViews.ts
[tsl] ERROR in /Users/<REDACTED>/web/src/redux/reducers/steppedViews.ts(13,53)
      TS2339: Property 'activeView' does not exist on type '{ activeView: number; } | { totalViews: number; }'.
  Property 'activeView' does not exist on type '{ totalViews: number; }'.

ERROR in /Users/<REDACTED>/web/src/redux/reducers/steppedViews.ts
./src/redux/reducers/steppedViews.ts
[tsl] ERROR in /Users/<REDACTED>/web/src/redux/reducers/steppedViews.ts(15,53)
      TS2339: Property 'totalViews' does not exist on type '{ activeView: number; } | { totalViews: number; }'.
  Property 'totalViews' does not exist on type '{ activeView: number; }'.

我的动作类型定义如下

export interface SetActiveView {
  type: typeof types.steppedViews.SET_ACTIVE_VIEW;
  payload: {
    activeView: number;
  };
}

export interface SetTotalViews {
  type: typeof types.steppedViews.SET_TOTAL_VIEWS;
  payload: { totalViews: number };
}

export type ReduxActionsSteppedViews = SetActiveView | SetTotalViews;

而我的 Reducer 是

import types from '../types';
import { ReduxActionsSteppedViews } from '../actions/steppedViews';

export interface ReduxStateSteppedView {
  activeView: number;
  totalViews: number;
}
const initialState: ReduxStateSteppedView = { activeView: 0, totalViews: 0 };

const reducer = (state = initialState, action: ReduxActionsSteppedViews): ReduxStateSteppedView => {
  switch (action.type) {
    case types.steppedViews.SET_ACTIVE_VIEW:
      return { ...state, activeView: action.payload.activeView };
    case types.steppedViews.SET_TOTAL_VIEWS:
      return { ...state, totalViews: action.payload.totalViews };
    default:
      return state;
  }
};

export default reducer;

我很困惑为什么会发生这种情况,因为根据我的理解,定义的类型是 '{activeView: number;} | {totalViews: number;}',因此它应该能够看到 *.activeView 或 *.totalViews。

任何关于此错误的指导都将不胜感激。谢谢!

1个回答

声明的类型为 {activeView: number;} | {totalViews: number;> ,因此 ReduxActionsSteppedViews.payload 中 activeView 和 totalViews 都不是必需的属性。>

Typescript 不知道您是否已完成类型检查(在您的情况下),因此您需要告诉她:

const reducer = (state = initialState, action: ReduxActionsSteppedViews): ReduxStateSteppedView => {
  switch (action.type) {
    case types.steppedViews.SET_ACTIVE_VIEW:
      return { ...state, activeView: (<SetActiveView> action).payload.activeView };
    case types.steppedViews.SET_TOTAL_VIEWS:
      return { ...state, totalViews:(< SetTotalViews> action).payload.totalViews };
    default:
      return state;
  }
};
glinda93
2020-07-17