'Redux Toolkit - How to have the payload type checked, when calling an action creator
I am using the redux toolkit for some time now and I like how it reduces boilerplate. I also want to use typescript, but I have trouble to make the typechecking of an action payload work.
f.i. I have:
const increase: CaseReducer<AppState, PayloadAction<number>> = (
state,
action,
) => {
state.usedWeight += action.payload;
};
and use this in createSlice. When I want to dispatch that action I write
dispatch(increase(10));
but I could also write
dispatch(increase("10"));
without typescript complaining.
When I hover the increase in the import in vs code it says:
const increase: ActionCreatorWithPayload<any, string> | ActionCreatorWithoutPayload<string>
Why does the ActionCreator not know, which Payload this Action is to expect?
Solution 1:[1]
Problem was that I had not used the CaseReducer directly in createSlice, but accumulated them in
const reducers: ValidateSliceCaseReducers<
AppState,
SliceCaseReducers<AppState>
> = {
### List of CaseReducers ###
}
The typing that I use here broke infering the types for the action creators later. (I think I got it from redux docs and used them, cause otherwise I would have to add AppState as Type of state to each reducer individually.)
My solution now is to put the CaseReducers directly into the createSlice call. In order to keep the slice clean, I will put those CaseReducers in subfiles.
Solution 2:[2]
I have the same problem.
Redux Toolkit provides a type guard with the action creator:
You could test, if increment.match(action) is true.
Type checking works then within the if statement, but not outside.
parseInt(action.payload, action.payload); // compiles without any error
if (increment.match(action)) {
parseInt(action.payload, action.payload); // here TypeScript produces an error
}
Shouldn't it be possible to ensure type checking without unsing such type guards? I would very much appreciate someone finding a better solution.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | OwnerOfThisIsle |
| Solution 2 | user8993702 |
