我正在尝试将我的reducer从JS转换为打字稿,但是却出现了一个我无法解决的怪异错误。错误来自于在化简器 [... state.messages] 中使用省略号进行数组解构。基本上,代码如下: 减速器:
import { HomeScreenAction } from '../actions';
import { HomeState, User, Message } from '../types';
import * as constants from '../constants';
import { combineReducers } from 'redux';
export function userState(state: HomeState = {}, action:
HomeScreenAction): HomeState {
switch (action.type) {
case constants.REQUEST_USER:
case constants.RECEIVE_USER:
return { user: action.user };
default:
return state;
}
}
export function messagesState(state: HomeState = {}, action:
HomeScreenAction):HomeState {
switch (action.type) {
case constants.REQUEST_MESSAGES:
case constants.RECEIVE_MESSAGES:
return { messages: action.messages };
case constants.Test1:
return{ ...state, user: action.payload};
case constants.Test2:
return {...state, messages:[ ...state.messages, action.payload ]};
default:
return state;
}
}
const rootReducer = combineReducers({
userState,
messagesState
});
export default rootReducer;
类型:
export interface HomeState {
user?: User;
messages?: Message[];
}
export interface Test1 {
type: typeof constants.Test1
payload: User
}
export interface Test2 {
type: typeof constants.Test2
payload: Message
}
和tsconfig.js:
"compilerOptions": {
/* Basic Options */
"target": "es6",
"watch": false,
"module": "commonjs",
"lib": [ "dom", "es6", "es2015" , "dom.iterable"],
// "allowJs": true,
// "checkJs": true,
"jsx": "react",
// "declaration": true,
"sourceMap": true,
// "outFile": "./",
"outDir": "./lib",
"strict": true
},
"include": ["./src/"]
}
我尝试了不同的库,例如es2015和es5,但仍然遇到
错误[...state.messages]
任何帮助将不胜感激。
答案 0 :(得分:0)
由于messages
是HomeState
中的可选属性,因此消息可以是undefined
,在这种情况下,数组解构将出现运行时错误。
为了防止运行时错误,TS抛出了编译时错误。
解决此问题的最简单方法是检查state.messages
是否为空并使用空数组初始化。示例:
case constants.Test2:
let messages: Message[] = state.mesaage || [];
return {...state, messages:[ ...messages, action.payload ]};