Search code examples
javascripttypescriptreduxreact-reduxredux-toolkit

Redux-Toolkit extraReducers listed after reducers causes issues (TS2322 Error)


Problem

I am using Redux-Toolkit and I am having an issue with the code below. When extraReducers is omitted, my code works fine. When extraReducers is listed after reducers, I encounter an error (shown below). When extraReducers is listed before reducers, my code works fine. What am I missing here?

type Item = { id: string, name: string }

export const itemsAdapter = createEntityAdapter<Item>();
const initialState = itemsAdapter.getInitialState();

export const slice = createSlice({
  name: 'items',
  initialState,
  reducers: {  
    itemsAdded(state, action: PayloadAction<{ items: Item[] }>) {
      itemsAdapter.setAll(state, action.payload.items);
    }, 
  },
  extraReducers: (builder) => { /*  },,
});

Error Message

TS2322: Type '(state: WritableDraft<EntityState<Item>>, action: { payload: { items: Item[]; }; type: string; }) => void' is not assignable to type 'CaseReducer<WritableDraft<EntityState<Item>> | undefined, { payload: any; type: string; }> | CaseReducerWithPrepare<WritableDraft<EntityState<Item>> | undefined, PayloadAction<...>>'.
  Type '(state: WritableDraft<EntityState<Item>>, action: { payload: { items: Item[]; }; type: string; }) => void' is not assignable to type 'CaseReducer<WritableDraft<EntityState<Item>> | undefined, { payload: any; type: string; }>'.
    Types of parameters 'state' and 'state' are incompatible.
      Type 'WritableDraft<WritableDraft<EntityState<Item>>> | undefined' is not assignable to type 'WritableDraft<EntityState<Item>>'.
        Type 'undefined' is not assignable to type 'WritableDraft<EntityState<Item>>'.

Solution

  • I fixed this by providing a type for the builder parameter.

    extraReducers: (builder: ActionReducerMapBuilder<MyCustomState>) => {
      builder.addCase(myCaseReducer, (state, action) => { /* this is code */ });
    }
    

    This prevents typescript from inferring MyCustomState | undefined

    Does seem like a bug, this wasn't a problem until I updated redux-toolkit