Z
Z
zlodiak2020-11-17 15:15:27
typescript
zlodiak, 2020-11-17 15:15:27

Why does the reducer not work without specifying the type?

I am using react-redux + typescript.

Here is the simplest redsuer I use:

type msgObjType = {
    name: string
    email: string
    msg: string
}

type msgObjActionType = {
    type: string
    payload: msgObjType
}

const msgReducer = function msgReducer(state = { msgs: [] as Array<msgObjType> }, action: msgObjActionType) {
    switch(action.type) {
        case 'ADD_MSG': {
            state = {
                ...state,
                msgs: [ ...state.msgs, action.payload ]
            };
            break;
        }              
        default:
            return state;
    }
    return state;
}

export const addMsgAC = (msgObj: msgObjType) => {
    return { type: 'ADD_MSG', payload: msgObj }
}

export default msgReducer;

It works without problems. Problems start when I remove typing: In this case, the following error message is displayed:

as Array<msgObjType>


Type 'msgObjType[]' is not assignable to type 'never[]'.
Type 'msgObjType' is not assignable to type 'never'. TS2322


Please help me understand what is the meaning of the error? I do not understand why in this case the presence of typing is critical?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-11-25
@zlodiak

You cannot assign msgObjType[] to type never[].)) Define the type for the state in advance.
interface IState {
msgs: msgObjType[];
}
const initialState: IState = {
msgs: []
}
const reducer = (state = initialState, ...);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question