Creating Typed Actions and Action Creators
Show how to define typed action constants and action creators, ensuring that the dispatched actions conform to the defined types.
// Define action types as constants
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
Defines two action types, INCREMENT and DECREMENT, to be used in the application.
// Action creators return objects conforming to the action types
function increment() {
return {
type: INCREMENT,
payload: 1
};
}
function decrement() {
return {
type: DECREMENT,
payload: -1
};
}
Creates two action creators, 'increment' and 'decrement', which return actions with respective types and payloads.
// Typed action interfaces (for TypeScript)
// interface IncrementAction {
// type: typeof INCREMENT;
// payload: number;
// }
//
// interface DecrementAction {
// type: typeof DECREMENT;
// payload: number;
// }
// // Use these interfaces to type-check the action creators
// function typedIncrement(): IncrementAction {
// return {
// type: INCREMENT,
// payload: 1,
// };
// }
//
// function typedDecrement(): DecrementAction {
// return {
// type: DECREMENT,
// payload: -1,
// };
// }
Optional TypeScript interfaces for typed actions and action creators, ensuring strict type checking.
// Using the action creators to dispatch actions
// dispatch(increment());
// dispatch(decrement());
Example usage of the action creators to dispatch actions, typically within a Redux-connected component.