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
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
StateandCaseReducerstypes 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.
Most helpful comment
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.