Defining Type-Safe Actions
Demonstrate how to define type-safe action creators with TypeScript in Redux v5.0.0 that help prevent type-related errors at compile time.
import { ActionCreator, Action } from 'redux';
// Defining the action types
export enum ActionTypes {
INCREMENT = 'INCREMENT',
DECREMENT = 'DECREMENT'
}
// Defining the shape of the increment and decrement actions
interface IncrementAction extends Action {
type: ActionTypes.INCREMENT;
payload: number;
}
interface DecrementAction extends Action {
type: ActionTypes.DECREMENT;
payload: number;
}
// Type for all action creators
type AppAction = IncrementAction | DecrementAction;
// Increment action creator
export const increment: ActionCreator<IncrementAction> = (value: number) => ({
type: ActionTypes.INCREMENT,
payload: value
});
// Decrement action creator
export const decrement: ActionCreator<DecrementAction> = (value: number) => ({
type: ActionTypes.DECREMENT,
payload: value
});
TypeScript code example that defines type-safe action creators using an enum for action types, and interfaces for each action. It also demonstrates how to use the ActionCreator generic to ensure the correct return type for each action creator function.