Redux TypeScript Actions
A simple Action Creator library for TypeScript. Its goal is to provide simple yet type-safe experience with Redux actions. Created actions are FSA-compliant:
Installation
npm install --save redux-typescript-actions
Usage
Basic
; ; // Specify payload shape as generic type argument. ; // Get action creator type.console.logsomethingHappened.type; // SOMETHING_HAPPENED // Create action.;console.logaction; // {type: 'SOMETHING_HAPPENED', payload: {foo: 'bar'}}
Async Action Creators
Async Action Creators are objects with properties started
, done
and
failed
whose values are action creators.
; ; // specify parameters and result shapes as generic type arguments , // success type // error type >'DO_SOMETHING'; console.logdoSomething.started;// {type: 'DO_SOMETHING_STARTED', payload: {foo: 'lol'}} console.logdoSomething.done;// {type: 'DO_SOMETHING_DONE', payload: {// params: {foo: 'lol'},// result: {bar: 42},// }} console.logdoSomething.failed;// {type: 'DO_SOMETHING_FAILED', payload: {// params: {foo: 'lol'},// error: {code: 42},// }, error: true}
Actions With Type Prefix
You can specify a prefix that will be prepended to all action types. This is useful to namespace library actions as well as for large projects where it's convenient to keep actions near the component that dispatches them.
// MyComponent.actions.ts; ; ; ;console.logaction; // {type: 'MyComponent/SOMETHING_HAPPENED', payload: {foo: 'bar'}}
Reducers
// actions.ts; ; ; // reducer.ts;;; ; ;
API
actionCreatorFactory(prefix?: string, defaultIsError?: Predicate): ActionCreatorFactory
Creates Action Creator factory with optional prefix for action types.
prefix?: string
: Prefix to be prepended to action types.defaultIsError?: Predicate
: Function that detects whether action is error given the payload. Default ispayload => payload instanceof Error
.
isType(action: Action, actionCreator: ActionCreator): boolean
Returns true
if action has the same type as action creator. Defines
Type Guard
that lets TypeScript know payload
type inside blocks where isType
returned
true
:
; if isTypeaction, somethingHappened