我正在尝试在我的React应用中使用Typescript
在我的mapStateToProps
中,我有此代码
const mapStateToProps = (state: AppState) => {
console.log(state)
return {
...state.player,
position: state.player.position
}
}
我的AppState
import { combineReducers } from 'redux';
import playerReducer from './player';
export const rootReducer = combineReducers({
player: playerReducer
} as any);
export type AppState = ReturnType<typeof rootReducer>
我遇到与行TypeScript error: Property 'player' does not exist on type '{}'. TS2339
有关的错误...state.player
但是,如果我console.log状态(在此之前的行中),我的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;
答案 0 :(得分:1)
问题是由于combineReducers
,as any
无法推断您要传递的对象的类型。这意味着您的根减速器只能通过以下类型来推断:
const rootReducer: Reducer<{}, AnyAction>;
只需取出as any
中的combineReducers
:
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) => {
...
};
我在项目中使用的 exact 模式将是这样的(当然,您可能需要对其进行调整,直到获得对项目更好的东西):
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;