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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s