Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

typesafe-actions

> 编程语言
Open source

Typesafe utilities for "action-creators" in Redux / Flux Architecture

2.4K stars0 likes2 views
WebsiteGitHub

About

Typesafe utilities for "action-creators" in Redux / Flux Architecture

Features

  • Easily create completely typesafe Actions or even Async Actions
  • No boilerplate and completely typesafe Reducers
  • Game-changing Helper Types for Redux

Examples

  • Todo-App playground: Codesandbox
  • React, Redux, TypeScript - RealWorld App: Github | Demo

Goals

  • Secure and Minimal - no third-party dependencies, according to size-snapshot (Minified: 3.48 KB, Gzipped: 1.03 KB), check also on bundlephobia
  • Optimized - distribution packages bundled in 3 different formats (cjs, esm and umd) with separate bundles for dev & prod (same as react)
  • Quality - complete test-suite for an entire API surface containing regular runtime tests and extra type-tests to guarantee type soundness and to prevent regressions in the future TypeScript versions
  • Performance - integrated performance benchmarks to guarantee that the computational complexity of types are in check and there are no slow-downs when your application grow npm run benchmark:XXX

Table of Contents

  • Installation
  • Tutorial v4 (v5 is WIP #188)
    • Constants
    • Actions
      • 1. Basic actions
      • 2. FSA compliant actions
      • 3. Custom actions (non-standard use-cases)
    • Action Helpers
      • Using action-creators instances instead of type-constants
      • Using regular type-constants
    • Reducers
      • Extending internal types to enable type-free syntax with createReducer
      • Using createReducer API with type-free syntax
      • Alternative usage with regular switch reducer
    • Async-Flows
      • With redux-observable epics
      • With redux-saga sagas
  • API Docs v4 (v5 is WIP #189)
    • Action-Creators API
      • action
      • createAction
      • createStandardAction
      • createCustomAction
      • createAsyncAction
    • Reducer-Creators API
      • createReducer
    • Action-Helpers API
      • getType
      • isActionOf
      • isOfType
    • Type-Helpers API
      • ActionType
      • StateType
  • Migration Guides
    • v4.x.x to v5.x.x
    • v3.x.x to v4.x.x
    • v2.x.x to v3.x.x
    • v1.x.x to v2.x.x
    • Migrating from redux-actions to typesafe-actions
  • Compatibility Notes
  • Recipes
    • Restrict Meta type in action creator
  • Compare to others
    • redux-actions
  • Motivation
  • Contributing
  • Funding Issues
  • License

Installation

bash
# NPM
npm install typesafe-actions

# YARN
yarn add typesafe-actions

⇧ back to top


Tutorial v4 (v5 is WIP #188)

To showcase the flexibility and the power of the type-safety provided by this library, let's build the most common parts of a typical todo-app using a Redux architecture:

WARNING
Please make sure that you are familiar with the following concepts of programming languages to be able to follow along: Type Inference, Control flow analysis, Tagged union types, Generics and Advanced Types.

⇧ back to top

Constants

RECOMMENDATION:
When using typesafe-actions in your project you won't need to export and reuse string constants. It's because action-creators created by this library have static property with action type that you can easily access using actions-helpers and then use it in reducers, epics, sagas, and basically any other place. This will simplify your codebase and remove some boilerplate code associated with the usage of string constants. Check our /codesandbox application to learn some best-practices to create such codebase.

Limitations of TypeScript when working with string constants - when using string constants as action type property, please make sure to use simple string literal assignment with const. This limitation is coming from the type-system, because all the dynamic string operations (e.g. string concatenation, template strings and also object used as a map) will widen the literal type to its super-type, string. As a result this will break contextual typing for action object in reducer cases.

typescript
// Example file: './constants.ts'

// WARNING: Incorrect usage
export const ADD = prefix + 'ADD'; // => string
export const ADD = `${prefix}/ADD`; // => string
export default {
   ADD: '@prefix/ADD', // => string
}

// Correct usage
export const ADD = '@prefix/ADD'; // => '@prefix/ADD'
export const TOGGLE = '@prefix/TOGGLE'; // => '@prefix/TOGGLE'
export default ({
  ADD: '@prefix/ADD', // => '@prefix/ADD'
} as const) // working in TS v3.4 and above => https://github.com/Microsoft/TypeScript/pull/29510

⇧ back to top

Actions

Different projects have different needs, and conventions vary across teams, and this is why typesafe-actions was designed with flexibility in mind. It provides three different major styles so you can choose whichever would be the best fit for your team.

1. Basic actions

action and createAction are creators that can create actions with predefined properties ({ type, payload, meta }). This makes them concise but also opinionated.

Important property is that resulting action-creator will have a variadic number of arguments and preserve their semantic names (id, title, amount, etc...).

These two creators are very similar and the only real difference is that action WILL NOT WORK with action-helpers.

typescript
import { action, createAction } from 'typesafe-actions';

export const add = (title: string) => action('todos/ADD', { id: cuid(), title, completed: false });
// add: (title: string) => { type: "todos/ADD"; payload: { id: string, title: string, completed: boolean; }; }

export const add = createAction('todos/ADD', action => {
  // Note: "action" callback does not need "type" parameter
  return (title: string) => action({ id: cuid(), title, completed: false });
});
// add: (title: string) => { type: "todos/ADD"; payload: { id: string, title: string, completed: boolean; }; }

2. FSA compliant actions

This style is aligned with Flux Standard Action, so your action object shape is constrained to ({ type, payload, meta, error }). It is using generic type arguments for meta and payload to simplify creation of type-safe action-creators.

It is important to notice that in the resulting action-creator arguments are also constrained to the predefined: (payload, meta), making it the most opinionated creator.

TIP: This creator is the most compatible with redux-actions in case you are migrating.

typescript
import { createStandardAction } from 'typesafe-actions';

export const toggle = createStandardAction('todos/TOGGLE')<string>();
// toggle: (payload: string) => { type: "todos/TOGGLE"; payload: string; }

export const add = createStandardAction('todos/ADD').map(
  (title: string) => ({
    payload: { id: cuid(), title, completed: false },
  })
);
// add: (payload: string) => { type: "todos/ADD"; payload: { id: string, title: string, completed: boolean; }; }

3. Custom actions (non-standard use-cases)

This approach will give us the most flexibility of all creators, providing a variadic number of named parameters and custom properties on action object to fit all the custom use-cases.

typescript
import { createCustomAction } from 'typesafe-actions';

const add = createCustomAction('todos/ADD', type => {
  return (title: string) => ({ type, id: cuid(), title, completed: false });
});
// add: (title: string) => { type: "todos/ADD"; id: string; title: string; completed: boolean; }

TIP: For more examples please check the API Docs.

RECOMMENDATION
Common approach is to create a RootAction in the central point of your redux store - it will represent all possible action types in your application. You can even merge it with third-party action types as shown below to make your model complete.

typescript
// types.d.ts
// example of including `react-router` actions in `RootAction`
import { RouterAction, LocationChangeAction } from 'react-router-redux';
import { TodosAction } from '../features/todos';

type ReactRouterAction = RouterAction | LocationChangeAction;

export type RootAction =
  | ReactRouterAction
  | TodosAction;

⇧ back to top

Action Helpers

Now I want to show you action-helpers and explain their use-cases. We're going to implement a side-effect responsible for showing a success toast when user adds a new todo.

Important thing to notice is that all these helpers are acting as a type-guard so they'll narrow tagged union type (RootAction) to a specific action type that we want.

Using action-creators instances instead of type-constants

Instead of type-constants we can use action-creators instance to match specific actions in reducers and epics cases. It works by adding a static property on action-creator instance which contains the type string.

The most common one is getType, which is useful for regular reducer switch cases:

typescript
  switch (action.type) {
    case getType(todos.add):
      // below action type is narrowed to: { type: "todos/ADD"; payload: Todo; }
      return [...state, action.payload];
    ...

Then we have the isActionOf helper which accept action-creator as first parameter matching actions with corresponding type passed as second parameter (it's a curried function).

…

Using regular type-constants

Alternatively if your team prefers to use regular type-constants you can still do that.

We have an equivalent helper (isOfType) which accept type-constants as parameter providing the same functionality.

…

TIP: you can use action-helpers with other types of conditional statements.

typescript
import { isActionOf, isOfType } from 'typesafe-actions';

if (isActionOf(actions.add, action)) {
  // here action is narrowed to: { type: "todos/ADD"; payload: Todo; }
}
// or with type constants
if (isOfType(types.ADD, action)) {
  //

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptaction-creatorjavascriptreduxredux-actions

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言