Redux Toolkit TypeScript createSlice Reducers in Different File

If you want to define your reducers in a separate file from you createSlice function and type it correctly, you need to type your state manually which was previously handled by createSlice.

We will need to create 2 files: one for your slice state type (to prevent future circular import issues), and one for your new reducer functions.

// slice.type.ts 
export type MySliceState {
   foo: string
}

Now we’ll make a reducer object in another file

// reducers.ts
import { CaseReducer } from "@reduxjs/toolkit";
import { MySliceState} from "./slice.type.ts";

const doSomething : CaseReducer<MySliceState> = (state, 
action:PayloadAction<{foo: string}>) => {
       // state is now typed to MySliceState
  }
export myReducers = {
  doSomething,
}
// mySlice.ts
export const photosSlice = createSlice({
  name: "mySlice",
  initialState: {} as MySliceState,
  reducers: {
    ...myReducers,
  },

Leave a Comment