redux-actions-type

easy typing of redux action

Usage no npm install needed!

<script type="module">
  import reduxActionsType from 'https://cdn.skypack.dev/redux-actions-type';
</script>

README

redux-actions-type

Build Status tested with jest styled with prettier All Contributors

easy typing of redux action

Install

$ npm install redux-actions-type
$ yarn add redux-actions-type

Usage

actions.ts

export const increment = (payload: number) =>
  ({
    type: 'increment',
    payload,
  } as const)

export const decrement = (payload: number) =>
  ({
    type: 'decrement',
    payload,
  } as const)

export const typo = (payload: string) =>
  ({
    // typo...
    typo: 'typo',
    payload,
  } as const)

types.ts

import { Reducer } from 'redux'
import { ActionType, ActionsType } from 'redux-actions-type'
import * as actions from './actions'

/**
 * @example
 * type Action = {
 *   type: "increment";
 *   payload: number;
 * } | {
 *   type: "decrement";
 *   payload: number;
 * }
 */
type Action = ActionType<typeof actions>

/**
 * @example
 * type Actions = {
 *   inc: {
 *     type: "increment";
 *     payload: number;
 *  };
 *  decrement: {
 *    type: "decrement";
 *    payload: number;
 *  };
 *  typo: never;
 * }
 */
type Actions = ActionsType<typeof actions>

/**
 * type IncrementAction = {
 *   type: "increment";
 *   payload: number;
 * }
 */
type IncrementAction = Actions['increment']

interface State {
  count: number
}

const reducer: Reducer<State, Action> = (
  state = { count: 0 },
  action: Action
) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + action.payload }
    case 'decrement':
      return { count: state.count - action.payload }
    // Type Error...
    // case 'typo':
    //   return { count: action.payload }
    default:
      return state
  }
}

Contributors

Thanks goes to these wonderful people (emoji key):

akameco
akameco

💻 📖 ⚠️ 🚇

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT © akameco