typesafe-actions
Typesafe utilities designed to reduce types verbosity and complexity in Redux Architecture.
This library is part of the React & Redux TypeScript Guide ecosystem 📖
Found it useful? Want more updates?
Show your support by giving a ⭐️
What's new?
🎉 Now updated to support TypeScript v3.7 🎉
⚠️ Library was recently updated to v5 ⚠️
Current API Docs and Tutorial are outdated (from v4), so temporarily please use this issue as v5.x.x API Docs.
Features
- Easily create completely typesafe Actions or even Async Actions
- No boilerplate and completely typesafe Reducers
- Game-changing Helper Types for Redux
Playgrounds & 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
andumd
) with separate bundles for dev & prod (same asreact
) - 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)
- API Docs v4 (v5 is WIP #189)
- Migration Guides
- Compatibility Notes
- Recipes
- Compare to others
- Motivation
- Contributing
- Funding Issues
- License
Installation
# NPM npm install typesafe-actions # YARN yarn add typesafe-actions
#188)
Tutorial v4 (v5 is WIPTo 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.
Constants
RECOMMENDATION:
When usingtypesafe-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.
// Example file: './constants.ts' // WARNING: Incorrect usage; // => string; // => string // Correct usage; // => '@prefix/ADD'; // => '@prefix/TOGGLE'
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 make 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...)
.
This two creators are very similar and the only real difference is that action
WILL NOT WORK with action-helpers.
; ;// add: (title: string) => { type: "todos/ADD"; payload: { id: string, title: string, completed: boolean; }; } ;// 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.
; ;// toggle: (payload: string) => { type: "todos/TOGGLE"; payload: string; } ;// 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.
; ;// 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 aRootAction
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.
// types.d.ts// example of including `react-router` actions in `RootAction`;; ; ;
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:
switch action.type { case getTypetodos.add: // below action type is narrowed to: { type: "todos/ADD"; payload: Todo; } return ; ...
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).
// epics.ts; ;
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.
// epics.ts; ;
TIP: you can use action-helpers with other types of conditional statements.
; if isActionOfactions.add, action // or with type constantsif isOfTypetypes.ADD, action
Reducers
createReducer
Extending internal types to enable type-free syntax with We can extend internal types of typesafe-actions
module with RootAction
definition of our application so that you don't need to pass generic type arguments with createReducer
API:
// types.d.ts; ; declare // now you can usecreateReducer...// instead ofcreateReducer...
Using createReducer API with type-free syntax
We can prevent a lot of boilerplate code and type errors using this powerfull and completely typesafe API.
Using handleAction chain API:
// using action-creators // state and action type is automatically inferred and return type is validated to be exact type .handleActionadd,state + action.payload .handleActionadd, ... // <= error is shown on duplicated or invalid actions .handleActionincrement,state + 1 .handleAction... // <= error is shown when all actions are handled // or handle multiple actions using array .handleAction,state + action.type === 'ADD' ? action.payload : 1 ; // all the same scenarios are working when using type-constantsconst counterReducer = createReducer0 .handleAction'ADD',state + action.payload .handleAction'INCREMENT',state + 1; counterReducer0, add4; // => 4counterReducer0, increment; // => 1
Alternative usage with regular switch reducer
First we need to start by generating a tagged union type of actions (TodosAction
). It's very easy to do by using ActionType
type-helper.
; ;;
Now we define a regular reducer function by annotating state
and action
arguments with their respective types (TodosAction
for action type).
Now in the switch cases we can use the type
property of action to narrowing the union type of TodosAction
to an action that is corresponding to that type.
switch action.type { case getTypeadd: // below action type is narrowed to: { type: "todos/ADD"; payload: Todo; } return ; ...
Async-Flows
redux-observable
epics
With To handle an async-flow of http request lets implement an epic
. The epic
will call a remote API using an injected todosApi
client, which will return a Promise that we'll need to handle by using three different actions that correspond to triggering, success and failure.
To help us simplify the creation process of necessary action-creators, we'll use createAsyncAction
function providing us with a nice common interface object { request: ... , success: ... , failure: ... }
that will nicely fit with the functional API of RxJS
.
This will mitigate redux verbosity and greatly reduce the maintenance cost of type annotations for actions and action-creators that would otherwise be written explicitly.
// actions.ts; ; // epics.ts;
redux-saga
sagas
With With sagas it's not possible to achieve the same degree of type-safety as with epics because of limitations coming from redux-saga
API design.
Typescript issues:
- Typescript does not currently infer types resulting from a
yield
statement so you have to manually assert the type e.g.const response: Todo[] = yield call(...
Here is the latest recommendation although it's not fully optimal. If you managed to cook something better, please open an issue to share your finding with us.
;; // Create the set of async actions; // Handle request saga // Main saga // Handle success reducer .handleActionfetchTodosAsync.success,;
#189)
API Docs v4 (v5 is WIPAction-Creators API
action
Simple action factory function to simplify creation of type-safe actions.
WARNING:
This approach will NOT WORK with action-helpers (such asgetType
andisActionOf
) because it is creating action objects while all the other creator functions are returning enhanced action-creators.
actiontype, payload?, meta?, error?)
Examples: > Advanced Usage Examples
;// { type: 'INCREMENT'; } ;// { type: 'CREATE_USER'; payload: { id: number; name: string }; } ;// { type: 'GET_USERS'; meta: string | undefined; }
TIP: Starting from TypeScript v3.4 you can achieve similar results using new
as const
operator.
;
createAction
Create an enhanced action-creator with unlimited number of arguments.
- Resulting action-creator will preserve semantic names of their arguments
(id, title, amount, etc...)
. - Returned action object have predefined properties
({ type, payload, meta })
createActiontypecreateActiontype,
TIP: Injected
actionCallback
argument is similar toaction
API but doesn't need the "type" parameter
Examples: > Advanced Usage Examples
; // - with type only;dispatchincrement;// { type: 'INCREMENT' }; // - with type and payload;dispatchadd10;// { type: 'ADD', payload: number } // - with type and meta;dispatchgetTodos'some_meta';// { type: 'GET_TODOS', meta: Params } // - and finally with type, payload and meta;dispatchgetTodo'some_id', 'some_meta';// { type: 'GET_TODO', payload: string, meta: string }
createStandardAction
Create an enhanced action-creator compatible with Flux Standard Action to reduce boilerplate and enforce convention.
- Resulting action-creator have predefined arguments
(payload, meta)
- Returned action object have predefined properties
({ type, payload, meta, error })
- But it also contains a
.map()
method that allow to map(payload, meta)
arguments to a custom action object({ customProp1, customProp2, ...customPropN })
createStandardActiontypecreateStandardActiontype<TPayload, TMeta?>createStandardActiontype.map
TIP: Using
undefined
as generic type parameter you can make the action-creator function require NO parameters.
Examples: > Advanced Usage Examples
; // Very concise with use of generic type arguments// - with type only;;increment; // { type: 'INCREMENT' } (no parameters are required) // - with type and payload;add10; // { type: 'ADD', payload: number } // - with type and meta;getDataundefined, 'meta'; // { type: 'GET_DATA', meta: string } // - and finally with type, payload and meta;getData1, 'meta'; // { type: 'GET_DATA', payload: number, meta: string } // Can map payload and meta arguments to a custom action object; dispatchnotify'Hello!', ;// { type: 'NOTIFY', from: string, message: string, messageType: MessageType, datetime: Date }
createCustomAction
Create an enhanced action-creator with unlimited number of arguments and custom properties on action object.
- Resulting action-creator will preserve semantic names of their arguments
(id, title, amount, etc...)
. - Returned action object have custom properties
({ type, customProp1, customProp2, ...customPropN })
createCustomActiontype,
Examples: > Advanced Usage Examples
; ; dispatchadd1;// { type: "CUSTOM"; customProp1: number; customProp2: number; }
createAsyncAction
Create an object containing three enhanced action-creators to simplify handling of async flows (e.g. network request - request/success/failure).
createAsyncAction requestType, successType, failureType, cancelType?)<TRequestPayload, TSuccessPayload, TFailurePayload, TCancelPayload?>
AsyncActionCreator
TIP: Using
undefined
as generic type parameter you can make the action-creator function require NO parameters.
Examples: > Advanced Usage Examples
; ; dispatchfetchUsersAsync.requestparams; dispatchfetchUsersAsync.successresponse; dispatchfetchUsersAsync.failureerr; ;fnfetchUsersAsync; // There is 4th optional argument to declare cancel action; dispatchfetchUsersAsync.cancel'reason'; ;fnfetchUsersAsync;
Reducer-Creators API
createReducer
Create a typesafe reducer
createReducerinitialState, handlersMap?)// orcreateReducerinitialState .handleActionactionCreator, reducer .handleAction, reducer .handleTypetype, reducer .handleType, reducer
Examples: > Advanced Usage Examples
TIP: You can use reducer API with a type-free syntax by Extending internal types, otherwise you'll have to pass generic type arguments like in below examples
// type-free syntax doesn't require generic type arguments
Object map style:
;;
Chain API style:
// using action-creators .handleActionadd,state + action.payload .handleActionincrement,state + 1 // handle multiple actions by using array .handleAction,state + action.type === 'ADD' ? action.payload : 1 ; // all the same scenarios are working when using type-constants .handleType'ADD',state + action.payload .handleType'INCREMENT',state + 1;
Extend or compose reducers - every operation is completely typesafe:
.handleAction'SUBTRACT',state - action.payload .handleAction'DECREMENT',state - 1;
Action-Helpers API
getType
Get the type property value (narrowed to literal type) of given enhanced action-creator.
getTypeactionCreator
Examples:
; ; // In switch reducerswitch action.type { case getTypeadd: // action type is { type: "ADD"; payload: number; } return state + action.payload; default: return state;} // or with conditional statementsif action.type === getTypeadd
isActionOf
Check if action is an instance of given enhanced action-creator(s) (it will narrow action type to a type of given action-creator(s))
WARNING: Regular action creators and action will not work with this helper
// can be used as a binary functionisActionOfactionCreator, action// or as a curried functionisActionOfactionCreatoraction// also accepts an arrayisActionOf, action// with its curried equivalentisActionOfaction
Examples: > Advanced Usage Examples
; // Works with any filter type function (`Array.prototype.filter`, lodash, ramda, rxjs, etc.)// - single action .filterisActionOfaddTodo // only actions with type `ADD` will pass .map
isOfType
Check if action type property is equal given type-constant(s) (it will narrow action type to a type of given action-creator(s))
// can be used as a binary functionisOfTypetype, action// or as curried functionisOfTypetypeaction// also accepts an arrayisOfType, action// with its curried equivalentisOfTypeaction
Examples: > Advanced Usage Examples
; // Works with any filter type function (`Array.prototype.filter`, lodash, ramda, rxjs, etc.)// - single action .filterisOfTypeADD // only actions with type `ADD` will pass .map
Type-Helpers API
Below helper functions are very flexible generalizations, works great with nested structures and will cover numerous different use-cases.
ActionType
Powerful type-helper that will infer union type from import * as ... or action-creator map object.
; // with "import * as ...";;// TodosAction: { type: 'action1' } | { type: 'action2' } | { type: 'action3' } // with nested action-creator map case;;// RootAction: { type: 'action1' } | { type: 'action2' } | { type: 'action3' }
StateType
Powerful type helper that will infer state object type from reducer function and nested/combined reducers.
WARNING: working with redux@4+ types
;; // with reducer function
Migration Guides
v4.x.x
to v5.x.x
Breaking changes:
- In
v5
all the deprecatedv4
creator functions are available underdeprecated
named import to help with incremental migration.
// before // after;
createStandardAction
was renamed tocreateAction
and.map
method was removed in favor of simplerredux-actions
style API.
// before; // after;
v4
version ofcreateAction
was removed. I suggest to refactor to use a newcreateAction
as in point2
, which was simplified and extended to supportredux-actions
style API.
// before; // after;
createCustomAction
- API was greatly simplified, now it's used like this:
// before; // after;
AsyncActionCreator
should be just renamed toAsyncActionCreatorBuilder
.
// before //after
v3.x.x
to v4.x.x
No breaking changes!
v2.x.x
to v3.x.x
Minimal supported TypeScript v3.1+
.
v1.x.x
to v2.x.x
Breaking changes:
createAction
- In
v2
we provide acreateActionDeprecated
function compatible withv1
createAction
to help with incremental migration.
// in v1 we created action-creator like this:; getTodo'some_id', 'some_meta'; // { type: 'GET_TODO', payload: 'some_id', meta: 'some_meta' } // in v2 we offer few different options - please choose your preference; ; ; ;
redux-actions
to typesafe-actions
Migrating from - createAction(s)
createActiontype, payloadCreator, metaCreator createStandardActiontype || createStandardActiontype.mappayloadMetaCreator createActions // COMING SOON!
- handleAction(s)
handleActiontype, reducer, initialState createReducerinitialState.handleActiontype, reducer handleActionsreducerMap, initialState createReducerinitialState, reducerMap
TIP: If migrating from JS -> TS, you can swap out action-creators from
redux-actions
with action-creators fromtypesafe-actions
in yourhandleActions
handlers. This works because the action-creators fromtypesafe-actions
provide the sametoString
method implementation used byredux-actions
to match actions to the correct reducer.
- combineActions
Not needed because each function in the API accept single value or array of values for action types or action creators.
Compatibility Notes
TypeScript support
5.X.X
- TypeScript v3.2+4.X.X
- TypeScript v3.2+3.X.X
- TypeScript v3.2+2.X.X
- TypeScript v2.9+1.X.X
- TypeScript v2.7+
Browser support
It's compatible with all modern browsers.
For older browsers support (e.g. IE <= 11) and some mobile devices you need to provide the following polyfills:
Recommended polyfill for IE
To provide the best compatibility please include a popular polyfill package in your application, such as core-js
or react-app-polyfill
for create-react-app
.
Please check the React
guidelines to learn how to do that: LINK
A polyfill fo IE11 is included in our /codesandbox
application.
Recipes
action
creator
Restrict Meta type in Using this recipe you can create an action creator with restricted Meta type with exact object shape.
; ; ; // OK! ; // Error// Object literal may only specify known properties, and 'excessProp' does not exist in type '{ eventName: string; }
Compare to others
Here you can find out a detailed comparison of typesafe-actions
to other solutions.
redux-actions
Lets compare the 3 most common variants of action-creators (with type only, with payload and with payload + meta)
Note: tested with "@types/redux-actions": "2.2.3"
- with type only (no payload)
redux-actions
;// resulting type:// () => {// type: string;// payload: void | undefined;// error: boolean | undefined;// }
with
redux-actions
you can notice the redundant nullablepayload
property and literal type oftype
property is lost (discrimination of union type would not be possible)
typesafe-actions
;// resulting type:// () => {// type: "NOTIFY";// }
with
typesafe-actions
there is no excess nullable types and no excess properties and the action "type" property is containing a literal type
- with payload
redux-actions
;// resulting type:// (t1: string) => {// type: string;// payload: { message: string; } | undefined;// error: boolean | undefined;// }
first the optional
message
parameter is lost,username
semantic argument name is changed to some generict1
,type
property is widened once again andpayload
is nullable because of broken inference
typesafe-actions
;// resulting type:// (username: string, message?: string | undefined) => {// type: "NOTIFY";// payload: { message: string; };// }
typesafe-actions
infer very precise resulting type, notice working optional parameters and semantic argument names are preserved which is really important for great intellisense experience
- with payload and meta
redux-actions
;// resulting type:// (...args: any[]) => {// type: string;// payload: { message: string; } | undefined;// meta: { username: string; message: string | undefined; };// error: boolean | undefined;// }
this time we got a completely broken arguments arity with no type-safety because of
any
type with all the earlier issues
typesafe-actions
/** * typesafe-actions */;// resulting type:// (username: string, message?: string | undefined) => {// type: "NOTIFY";// payload: { message: string; };// meta: { username: string; message: string | undefined; };// }
typesafe-actions
never fail toany
type, even with this advanced scenario all types are correct and provide complete type-safety and excellent developer experience
Motivation
When I started to combine Redux with TypeScript, I was trying to use redux-actions to reduce the maintainability cost and boilerplate of action-creators. Unfortunately, the results were intimidating: incorrect type signatures and broken type-inference cascading throughout the entire code-base (click here for a detailed comparison).
Existing solutions in the wild have been either too verbose because of redundant type annotations (hard to maintain) or used classes (hinders readability and requires using the new keyword 😱)
So I created typesafe-actions
to address all of the above pain points.
The core idea was to design an API that would mostly use the power of TypeScript type-inference 💪 to lift the "maintainability burden" of type annotations. In addition, I wanted to make it "look and feel" as close as possible to the idiomatic JavaScript ❤️ , so we don't have to write the redundant type annotations that which will create additional noise in your code.
Contributing
You can help make this project better by contributing. If you're planning to contribute please make sure to check our contributing guide: CONTRIBUTING.md
Funding Issues
You can also help by funding issues. Issues like bug fixes or feature requests can be very quickly resolved when funded through the IssueHunt platform.
I highly recommend to add a bounty to the issue that you're waiting for to increase priority and attract contributors willing to work on it.
License
Copyright (c) 2017 Piotr Witek piotrek.witek@gmail.com (http://piotrwitek.github.io)