I have some question about the type-save implementation of Redux in a Typescript React App.
I have done Setup and type-checking on Reducer and also using useTypedSelector from react-redux. Here, only one thing that i have inside the case Statements of Reducer a loose type-checking but that's not so problematically.
My Setup of the Redux Store:
// --------------------------------------- REDUX STORE ---------------------------------------
interface ITimePreset {
session: number;
break: number;
}
const UPDATE_TIMEPRESET = 'UPDATE_TIMEPRESET';
const INCREMENT_TIMEPRESET = 'INCREMENT_TIMEPRESET';
const DECREMENT_TIMEPRESET = 'DECREMENT_TIMEPRESET';
const BREAK = 'break';
const SESSION = 'session';
type Item = typeof BREAK | typeof SESSION;
interface IUpdateTimepresetAction {
type: typeof UPDATE_TIMEPRESET;
payload: {
value: number;
item: Item;
};
}
interface IIncrementTimepresetAction {
type: typeof INCREMENT_TIMEPRESET;
payload: Item;
}
interface IDecrementTimepresetAction {
type: typeof DECREMENT_TIMEPRESET;
payload: Item;
}
type TimePresetActionTypes = IUpdateTimepresetAction | IIncrementTimepresetAction | IDecrementTimepresetAction;
const initialState: ITimePreset = {
session: 25,
break: 5,
};
const timePresetReducer = (state: ITimePreset = initialState, action: TimePresetActionTypes): ITimePreset => {
switch (action.type) {
case UPDATE_TIMEPRESET:
return {
...state,
[action.payload.item]: action.payload.value,
};
case INCREMENT_TIMEPRESET:
return {
...state,
[action.payload]: state[action.payload] + 1,
};
case DECREMENT_TIMEPRESET:
return {
...state,
[action.payload]: state[action.payload] - 1,
};
default:
return state;
}
};
const rootReducer = combineReducers({
timePreset: timePresetReducer,
});
type RootState = ReturnType<typeof rootReducer>;
const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector;
const store = createStore(rootReducer);
Usage of the useTypedSelector with nice type-checking is pretty fine:
const timePreset: ITimePreset = useTypedSelector(state => state.timePreset);
But for useDispatch i doesn't found a Solution for type-checking:
const dispatch = useDispatch();
// This is the correct one:
dispatch({ type: DECREMENT_TIMEPRESET, payload: element });
// Wrong one with no error
dispatch({ type: 'Whaaat', payload: 9 });
Is there a way for a type-checking on useDispatch Parameters? Did you have other suggestions for Implementation of Redux Store (Some best Practices)-> This is my very first Example.