1.0.2 • Published 5 years ago

typescript-fsa-creator v1.0.2

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

typescript-fsa-creator

Simple type-safe FSA(flux standard action) creator for TypeScript.

Installation

npm install --save typescript-fsa-creator

Usage

  1. Import typescript-fsa-creator
import { createAction, ActionsUnion } from 'typescript-fsa-creator'
  1. 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' } }),
  ...
}
  1. 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
      }
  ...