Redux-toolkit: Is it possible to type action payloads?

Created on 11 Mar 2021  路  8Comments  路  Source: reduxjs/redux-toolkit

Here's a simple usecase, pulled from https://redux-toolkit.js.org/usage/usage-with-typescript#createslice:

type State = number;

const increment: CaseReducer<State, PayloadAction<number>> = (state, action) =>
  state + action.payload

const exampleSlice = createSlice({
  name: 'test',
  initialState: 0,
  reducers: {
    increment
  }
});
exampleSlice.actions.increment('a string') // no type error on the action payload

Most helpful comment

I have figured it out. I was defining the State and CaseReducers types when creating my slice:

const userSlice = createSlice<
  UserStateSlice,
  SliceCaseReducers<UserStateSlice>
>({...})

Removing those types fixes things. I can't remember _why_ i added those types.

Thanks again for validating this!

Yes, you should never provide generic attributes to createSlice. You would need to re-type the whole slice essentially twice with no benefit at all - and mask errors as seen here.

All 8 comments

You are not calling an action, but are directly calling your case reducer in that example

Apologies, i have updated the example.

Just saw the edit: this does give an error, check it in this playground

Your TypeScript setup might be screwed up in some way.

Interesting, many thanks. I will do some research as to why i'm not getting typed action payloads, and will update and close this issue once i've figured it out.

Just as a hint: Check your IDE. If it's IntelliJ/WebStorm, that's probably the reason. They do not use the TypeScript compiler for most of their type hints, but a "faster approximation", which really does not work out well.

I have figured it out. I was defining the State and CaseReducers types when creating my slice:

const userSlice = createSlice<
  UserStateSlice,
  SliceCaseReducers<UserStateSlice>
>({...})

Removing those types fixes things. I can't remember _why_ i added those types.

Thanks again for validating this!

(About your previous comment, I'm using vscode and have set the typescript.tsdk to use the local typescript compiler.)

I have figured it out. I was defining the State and CaseReducers types when creating my slice:

const userSlice = createSlice<
  UserStateSlice,
  SliceCaseReducers<UserStateSlice>
>({...})

Removing those types fixes things. I can't remember _why_ i added those types.

Thanks again for validating this!

Yes, you should never provide generic attributes to createSlice. You would need to re-type the whole slice essentially twice with no benefit at all - and mask errors as seen here.

Was this page helpful?
0 / 5 - 0 ratings