Typesafe Action Creators for Redux

5.1.0 · active · verified Tue Apr 21

Typesafe-actions is a lightweight utility library designed to simplify and enhance type safety in Redux and Flux architectures, particularly within TypeScript projects. Currently at version 5.1.0, it focuses on reducing boilerplate and complexity in defining actions and reducers. The library ships with minimal external dependencies, emphasizing a secure and performant codebase. It provides robust tools for creating fully typesafe action creators (including synchronous and asynchronous actions), and streamlined reducer definitions. Typesafe-actions differentiates itself by offering extensive type-testing to ensure soundness across TypeScript versions and provides optimized builds for various environments (CJS, ESM, UMD). While it offers a powerful approach to Redux type safety, it's worth noting that Redux Toolkit is the officially recommended solution by the Redux team, which also offers strong TypeScript integration.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the creation of typesafe actions and a reducer using `typesafe-actions` in TypeScript, including how to define state, actions with payloads, and combine them into a reducer that handles different action types.

import { createAction, createReducer, ActionType } from 'typesafe-actions';

// 1. Define Actions
const increment = createAction('INCREMENT')<number>();
const decrement = createAction('DECREMENT')<void>();
const reset = createAction('RESET')();

const actions = {
  increment,
  decrement,
  reset
};

type RootAction = ActionType<typeof actions>;

interface CounterState {
  count: number;
}

const initialState: CounterState = {
  count: 0
};

// 2. Create a Reducer
const counterReducer = createReducer<CounterState, RootAction>(initialState)
  .handleAction(increment, (state, action) => ({
    ...state,
    count: state.count + action.payload
  }))
  .handleAction(decrement, (state) => ({
    ...state,
    count: state.count - 1
  }))
  .handleAction(reset, (state) => ({
    ...state,
    count: 0
  }));

// Example Usage (simulate Redux store)
let currentState = initialState;

console.log('Initial State:', currentState);

currentState = counterReducer(currentState, actions.increment(5));
console.log('After Increment by 5:', currentState);

currentState = counterReducer(currentState, actions.decrement());
console.log('After Decrement:', currentState);

currentState = counterReducer(currentState, actions.reset());
console.log('After Reset:', currentState);

view raw JSON →