Blog>
Snippets

Migrating from Any to Unknown for Action Types

Explain the process of migrating from 'any' to 'unknown' for action payload types in TypeScript to enhance type safety and demonstrate this with a code example.
// Initial setup using 'any' for the action payload
interface ActionAny {
  type: string;
  payload: any; // This is unsafe, as 'any' could be anything
}

// Function that dispatches an action
function dispatchAnyAction(action: ActionAny) {
  // Action dispatch logic...
}

// Example usage of dispatching with 'any'
dispatchAnyAction({
  type: 'UPDATE_SESSION',
  payload: 123 // This is not type-checked
});
This is the original code using 'any'. This code is unsafe because 'any' turns off TypeScript checks.
// Migration to 'unknown' for improved type safety
interface ActionUnknown {
  type: string;
  payload: unknown; // More type-safe than 'any'
}

// Function that dispatches an action with stricter type checking
function dispatchUnknownAction(action: ActionUnknown) {
  // Extra type checks can be performed here
  if (typeof action.payload === 'number') {
    // Handle number payload
  } else if (typeof action.payload === 'string') {
    // Handle string payload
  }
  // Action dispatch logic...
}

// Example usage of dispatching with 'unknown'
dispatchUnknownAction({
  type: 'UPDATE_SESSION',
  payload: 123 // Now, we must ensure payload is of the expected type
});
This code shows the migration to 'unknown' which forces the developer to perform type checks before using the payload, enhancing type safety.