Blog>
Snippets

Implementing UnknownAction Type Safety

Show how to define an UnknownAction type and use it in a Redux reducer to ensure type safety.
// Define UnknownAction type
interface UnknownAction {
    type: unknown;
    [extraProps: string]: unknown;
}
This piece of code defines the UnknownAction type, which has a 'type' property of unknown type, meaning it can be any type, and an index signature to handle any additional properties.
// Define known action types
interface IncrementAction {
    type: 'INCREMENT';
}

interface DecrementAction {
    type: 'DECREMENT';
}
Here, we define the known action types for increment and decrement with a specific 'type' property.
// Redux reducer with UnknownAction type safety
function counterReducer(state = 0, action: UnknownAction | IncrementAction | DecrementAction) {
    switch (action.type) {
        case 'INCREMENT':
            // Narrow down the type to IncrementAction
            return state + 1;
        case 'DECREMENT':
            // Narrow down the type to DecrementAction
            return state - 1;
        default:
            // Ensure the default case returns the unmodified state
            return state;
    }
}
The reducer is enhanced with type safety by accepting both UnknownAction and known action types. The switch statement handles known actions and returns the unmodified state for unknown actions.