Create and handle safely typed actions
Clone or download
Latest commit 595bb58 Dec 12, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.circleci Add .circleci/config.yml Oct 10, 2018
src Batman Oct 10, 2018
.gitignore Batman Oct 10, 2018
.npmignore Add .npmignore Oct 10, 2018
.prettierignore Batman Oct 10, 2018
.prettierrc Batman Oct 10, 2018
LICENSE.md Batman Oct 10, 2018
jest.config.js Batman Oct 10, 2018
package.json v1.0.5 Dec 12, 2018
readme.md Update readme.md Dec 12, 2018
tsconfig.json Fix build script Oct 10, 2018
yarn.lock Update readme.md Dec 12, 2018

readme.md

safe-redux 🌲

npm version CircleCI

NOTE: this library is based on @martin_hotell's rex-tils library and his article Improved Redux type safety with TypeScript 2.8.

Instead of telling the program what types it should use, types are inferred from the implementation, so type checker gets out of our way!

Improved Redux type safety with TypeScript 2.8

Install

yarn add @housinganywhere/safe-redux

npm i @housinganywhere/safe-redux

Use

Define the actions:

// src/pages/MyPage/actions.ts

import { ActionsUnion, createAction } from '@housinganywhere/safe-redux';

export const INC = '[counter] increment';
export const DEC = '[counter] decrement';
export const INC_BY = '[counter] increment_by';
export const WITH_META = '[counter] with_meta';

export const Actions = {
  inc: () => createAction(INC),
  dec: () => createAction(DEC),
  incBY: (by: number) => createAction(INC_BY, by),
  withMeta: (by: number, meta: string) => createAction(WITH_META, by, meta),
};

export type Actions = ActionsUnion<typeof Actions>;

export type ActionTypes =
  | typeof INC
  | typeof DEC
  | typeof INC_BY
  | typeof WITH_META;

Handle the actions:

// src/pages/MyPage/reducer.ts

import { handleActions } from '@housinganywhere/safe-redux';

import { User } from '../types';

import { INC, DEC, INC_BY, WITH_META, Actions, ActionTypes } from './actions';

interface State {
  count: number;
}

const initialState: State = {
  count: 0,
};

const reducer = handleActions<State, ActionTypes, Actions>(
  {
    [INC]: ({ count }) => ({ count: count + 1 }),
    [DEC]: ({ count }) => ({ count: count - 1 }),
    [INC_BY]: ({ count }, { payload }) => ({ count: count + payload }),
    [WITH_META]: ({ count }, { payload }) => ({ count: count + payload }),
  },
  initialState,
);

export default reducer;

Differences with rex-tils

  • Actions created by createAction are compliant with flux-standard-actions, meaning they have an error property set to true when the payload is instanceof Error and might have a meta property.
  • Added handleActions to create type safe reducers.
  • Smaller API. safe-redux only exports a few functions and types:
    • Functions: createAction and handleActions.
    • Types: Action, ActionsUnion and ActionsOfType.