Type-safe action creators with generics
Show how to use TypeScript generics to create type-safe action creators that infer the payload type in Redux 5.0.0.
interface Action<Type extends string, Payload> {
type: Type;
payload: Payload;
}
function createAction<Type extends string, Payload>(type: Type, payload: Payload): Action<Type, Payload> {
return { type, payload };
}
Defines a generic Action interface and a createAction function that takes a type and payload as arguments, returning an action object that enforces type-safety for both the action type and the payload.
const INCREMENT = 'INCREMENT';
const ADD_TODO = 'ADD_TODO';
interface IncrementPayload {
amount: number;
}
interface TodoPayload {
text: string;
}
// Action creators
const increment = (amount: number) => createAction(INCREMENT, { amount });
const addTodo = (text: string) => createAction(ADD_TODO, { text });
Defines specific action type constants and payload interfaces for each action. It then creates type-safe action creators using the generic createAction function previously defined.
// Using the action creators
const actionIncrement = increment(10);
const actionAddTodo = addTodo('Learn TypeScript');
Utilizes the type-safe action creators to create actions. The variables actionIncrement and actionAddTodo are inferred to have the appropriate action types and payload structures.