在类型“{}”上不存在属性。

4

我正在尝试在我的React应用程序中使用Typescript。

在我的mapStateToProps中,我有以下代码:

const mapStateToProps = (state: AppState) => {
    console.log(state)
    return {
        ...state.player,
        position: state.player.position
    }
}

我的应用状态

import { combineReducers } from 'redux';
import playerReducer from './player';

export const rootReducer = combineReducers({
  player: playerReducer
} as any);

export type AppState = ReturnType<typeof rootReducer>

我遇到一个错误: TypeScript 错误:类型“{}”上不存在属性“player”。 TS2339,是与这行代码 ...state.player 相关的。

但如果我在那行代码之前使用 console.log 输出 state 的值,state 就会显示有 player 属性。

我不确定为什么会出现这个错误。非常感谢任何帮助。

Player Reducer

import { Action } from '../actions/types';
import { Store } from '../types';


export const initialState: Store = {
  position: [410, 0]
};


const playerReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case 'MOVE_PLAYER':
      return {
        ...state,
        position: action.payload
      }   
    default:
      return state;
  }
}

export default playerReducer;
1个回答

3
问题在于combineReducers无法推断出你传入的对象的类型,因为使用了as any。这意味着你的根reducer只能被推断为以下类型:
const rootReducer: Reducer<{}, AnyAction>;

只需要在combineReducers中删除as any即可:
export const rootReducer = combineReducers({
  player: playerReducer
});

应该理解为:
const rootReducer: Reducer<{
  player: PlayerState;
}, AnyAction>;

尝试为您的playerReducer进行强类型化:
import { Action, Reducer } from "redux";

const playerReducer: Reducer<Store, Action> = (state = initialState, a) => {
    ...
};

我在我的项目中使用的确切模式可能类似于以下内容(当然,您可能希望对其进行微调,直到获得更符合您的项目要求的结果):

import { Action, Reducer } from "redux";
import { MOVE_PLAYER } from "../actions/playerActions"; // list all relevant actions here

export interface PlayerState {
  readonly position: [number, number];
}

const initialState: PlayerState = {
  position: [410, 0];
};

const reducers: { [k: string]: (s: PlayerState, a: any) => PlayerState } = {
  [MOVE_PLAYER]: (s, a: { payload: [number, number] }) => ({ ...s, position: a.payload }),
  // other player reducers
}

const reducer: Reducer<PlayerState, Action> = (s = initialState, a) => {
  const f = reducers[a.type];
  return typeof f === "function" ? f(s, a) : s;
};
export default reducer;

1
现在我在这一行 player: playerReducer 遇到了错误。 错误为 TypeScript 错误:类型 '(state: Store | undefined, action: ActionA) => Store | { position: string; }' 不能赋值给类型 'Reducer<Store | { position: string; }, AnyAction>'。 参数 'state' 和 'state' 的类型不兼容。 类型 'Store | { position: string; } | undefined' 不能赋值给类型 'Store | undefined'。 类型 '{ position: string; }' 不能赋值给类型 'Store'。 属性 'position' 的类型不兼容。 - Person

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接