Ensuring Action Payload Types
Define a TypeScript type for the action payload to ensure correct types are dispatched to the Redux store, thus preventing type issues before they impact the store state.
interface AddTodoAction {
type: 'ADD_TODO';
payload: {
text: string;
};
}
interface ToggleTodoAction {
type: 'TOGGLE_TODO';
payload: {
index: number;
};
}
type TodoAction = AddTodoAction | ToggleTodoAction;
function addTodo(text: string): AddTodoAction {
return {
type: 'ADD_TODO',
payload: { text }
};
}
function toggleTodo(index: number): ToggleTodoAction {
return {
type: 'TOGGLE_TODO',
payload: { index }
};
}
Defines TypeScript action types for adding and toggling todos, and action creators ensuring the payload types match the defined interfaces.
const rootReducer = (state: TodoState = initialState, action: TodoAction) => {
switch (action.type) {
case 'ADD_TODO':
// Handle ADD_TODO
return {
...state,
todos: [...state.todos, { text: action.payload.text, completed: false }]
};
case 'TOGGLE_TODO':
// Handle TOGGLE_TODO
return {
...state,
todos: state.todos.map((todo, index) =>
index === action.payload.index ? { ...todo, completed: !todo.completed } : todo
)
};
default:
return state;
}
};
A reducer function named 'rootReducer' that takes action objects with the specified type and payload structure and updates the state accordingly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App</title>
<style>
/* Add your styles here */
</style>
</head>
<body>
<div id="app">
<!-- Your app's HTML goes here -->
</div>
<script src="path/to/your/compiled/typescript.js"></script>
</body>
</html>
The basic structure of an HTML document that will host our app, linking to the compiled TypeScript file that contains our types and state management functions.