Blog>
Snippets

Action Type Constants and Enums in TypeScript

Show how to define action type constants as TypeScript enums or string literals in a Redux application, enforcing type safety in action creators and reducers.
// Define action types as TypeScript enum
enum ActionTypes {
    ADD_TODO = 'ADD_TODO',
    TOGGLE_TODO = 'TOGGLE_TODO',
    SET_FILTER = 'SET_FILTER'
}
This code defines an enum called 'ActionTypes' for a Redux application, which contains various action types as enum members. Each member is assigned a string that corresponds with the action type it represents.
// Define action types as TypeScript string literals for type safety
const ADD_TODO = 'ADD_TODO' as const;
const TOGGLE_TODO = 'TOGGLE_TODO' as const;
const SET_FILTER = 'SET_FILTER' as const;
This code snippet uses TypeScript string literals with the 'as const' assertion to define action type constants in a way that makes them read-only and ensures type safety.
// Action creator using TypeScript enum for type-safe actions
function addTodoActionCreator(description: string) {
    return {
        type: ActionTypes.ADD_TODO,
        payload: { description }
    };
}
This code demonstrates an action creator function called 'addTodoActionCreator' which uses the ActionTypes enum to specify the action type, ensuring that only valid action types can be dispatched.
// Reducer using TypeScript enum to handle actions type-safely
function todoReducer(state = [], action: { type: ActionTypes, payload: any }) {
    switch (action.type) {
        case ActionTypes.ADD_TODO:
            return [...state, action.payload];
        case ActionTypes.TOGGLE_TODO:
            // Logic to toggle todo
            return state;
        case ActionTypes.SET_FILTER:
            // Logic to set a filter
            return state;
        default:
            return state;
    }
}
This code is a reducer function called 'todoReducer' which uses the ActionTypes enum in a switch statement to handle different action types with type safety. Each case applies the corresponding logic based on the action type.
// HTML and CSS are not applicable for this TypeScript example.
There is no HTML or CSS code provided since this example is centered around TypeScript action types in a Redux application context.