typescript-fsa-creator
v1.0.2
Published
simple type-safe flux standard action creator
Downloads
5
Maintainers
Readme
typescript-fsa-creator
Simple type-safe FSA(flux standard action) creator for TypeScript.
Installation
npm install --save typescript-fsa-creator
Usage
- Import
typescript-fsa-creator
import { createAction, ActionsUnion } from 'typescript-fsa-creator'
- Define a dictionary of action creators by
createAction
.
const actionCreators = {
// createAction('action type') or
// createAction('action type', { error?: {}, payload?: {}, meta?: {} })
simple: () => createAction('SIMPLE'),
withPayload: (payload1: string) => createAction(
'WITH_PAYLOAD', { payload: { payload1 } }),
withError: (errorDetails: string) => createAction(
'WITH_ERROR', { error: true }),
withMeta: () => createAction(
ActionType.WITH_META,
{ meta: { meta1: 'foo' } }),
...
}
- Define the action union.
type Action = ActionsUnion <type of actionCreators>
After that, types of actions can be resolved in switch
sentence by using Action
.
interface State {
error: boolean,
payload: string,
meta: string
}
const reducer = (
state: State,
action: Action
) => {
switch (action.type) {
case ActionType.SIMPLE:
return state
case ActionType.WITH_PAYLOAD:
return {
...state,
payload: action.payload!.payload1
}
case ActionType.WITH_ERROR:
return {
...state,
error: action.error!
}
case ActionType.WITH_META:
return {
...state,
meta: action.meta!.meta1
}
...