Blog>
Snippets

TypeScript Unknown Action Type Guard

Using TypeScript, create a type guard that ensures an action is known before it is processed, helping to avoid runtime errors.
// Define the known action types as a string literal type
Defines the string literal types for the known actions to ensure TypeScript can check for them.
type KnownAction = 'LOAD_DATA' | 'UPDATE_DATA' | 'DELETE_DATA';
Actual declaration of the known actions.
// Define the action interface with a type property
Creates an interface for actions including a type property to discriminate between actions.
interface Action {
  type: string;
  payload?: any;
}
// Type guard function to determine if an action is a known action
Type guard function that uses the KnownAction type to check if an action's type property is a known action.
function isKnownAction(action: Action): action is Action & { type: KnownAction } {
  return ['LOAD_DATA', 'UPDATE_DATA', 'DELETE_DATA'].includes(action.type);
}
// Usage example of the type guard within a reducer function
An example showing how to use the type guard in a reducer function to ensure type safety.
function reducer(state: any, action: Action) {
  if (isKnownAction(action)) {
    // Process the known action safely, as its type is now narrowed
    switch (action.type) {
      case 'LOAD_DATA':
Handle the 'LOAD_DATA' action
        // Handle loading data
        break;
      case 'UPDATE_DATA':
Handle the 'UPDATE_DATA' action
        // Handle updating data
        break;
      case 'DELETE_DATA':
Handle the 'DELETE_DATA' action
        // Handle deleting data
        break;
      default:
Ensures exhaustive checks, TypeScript will error if a case is not handled
        // If it gets here, the action type is not known, you may throw an error or handle it as you see fit
    }
  } else {
In case the action type is not known, this block can be used to handle or log an error.
    // Handle or log an error because the action type is unknown
  }
  return state;
Return state at the end of the reducer function
}
End of the reducer function