Socket
Socket
Sign inDemoInstall

ts-redux-actions

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-redux-actions

Typed Redux Actions for TypeScript Projects


Version published
Weekly downloads
3
Maintainers
1
Weekly downloads
 
Created
Source

TS Redux Actions

Redux helpers for Type-safety (action types & action creators)

From now on no type errors will sneak in unnoticed through your action creators!

  • Semantic Versioning
  • No external dependencies
  • Output separate bundles for your specific workflow needs:
    • ES5 + CommonJS - main
    • ES5 + ES-Modules - module
    • ES2015 + CommonJS - jsnext:main

Table of Contents (v1.0)

  • Motivation
  • Usage
  • API

Motivation

I wasn't satisfied with the API design in redux-actions. The reason was because of the specific API design (allowing multiple args for action creator) and separate payload, meta map functions which is not good for static typing in TypeScript. It doesn't allow for correct type inference and it will force you to do an extra effort for explicit type annotations and produce more boilerplate.

The most issues with redux-actions types and similar solutions are related to losing your function definition inference and intellisense (named arguments and arity) in resulting action creator function which for me is unacceptable.

As a bonus you can use a convenient type static property on every action creator for reducer switch case scenarios (working with narrowing of union types):

const increment = createAction('INCREMENT');

switch (action.type) {
  case increment.type:
    return state + 1;
  ...
  ...
  default: return state;
}

Usage

To highlight the difference in API design and the benefits of "action creator" type inference found in this solution let me show you some usage examples:

  • no payload
// with redux-actions
const notify1 = createAction('NOTIFY')
// notice excess nullable properties "payload" and "error", "type" property widened to string
// const notify1: () => {
//   type: string;
//   payload: void | undefined;
//   error: boolean | undefined;
// }

// with ts-redux-actions
const notify1 = createAction('NOTIFY')
// only what is expected, no nullables, with inferred literal type in type property!
// const notify1: () => {
//   type: "NOTIFY";
// }
  • with payload
// with redux-actions
const notify2 = createAction('NOTIFY',
  (username: string, message?: string) => ({
    message: `${username}: ${message}`
  })
)
// notice missing optional "message" argument, arg name changed to "t1", "type" property widened to string, and excess nullable properties
// const notify2: (t1: string) => {
//   type: string;
//   payload: { message: string; } | undefined;
//   error: boolean | undefined;
// }

// with ts-redux-actions
const notify2 = createAction('NOTIFY', (type: 'NOTIFY') =>
  (username: string, message?: string) => ({
    type,
    payload: { message: `${username}: ${message}` },
  })
)
// still all good!
// const notify2: (username: string, message?: string | undefined) => {
//   type: "NOTIFY";
//   payload: { message: string; };
// }

  • with payload and meta
// with redux-actions
const notify3 = createAction('NOTIFY',
  (username: string, message?: string) => ({ message: `${username}: ${message}` }),
  (username: string, message?: string) => ({ username, message })
)
// notice missing arguments arity and types, "type" property widened to string
// const notify2: (...args: any[]) => {
//   type: string;
//   payload: { message: string; } | undefined;
//   meta: { username: string; message: string | undefined; };
//   error: boolean | undefined;
// }

// with ts-redux-actions
const notify3 = createAction('NOTIFY', (type: 'NOTIFY') =>
    (username: string, message?: string) => ({
      type,
      payload: { message: `${username}: ${message}` },
      meta: { username, message },
    }),
  )

// inference working as expected and compiler will catch all those nasty bugs:
// const: notify: (username: string, message?: string | undefined) => {
//   type: "NOTIFY";
//   payload: { message: string; };
//   meta: { username: string; message: string | undefined; };
// }

API

For more advanced usage scenarios please check use cases described in test specification

createAction

> Advanced Usage

createAction(type, creatorFunction?)
type: string,
creatorFunction: (type: T) => (...args: any[]) => { type: T, payload?: P, meta?: M }
return: (...args: any[]) => { type: T, payload?: P, meta?: M }

Examples:

it('no payload', () => {
  const increment = createAction('INCREMENT');

  expect(increment()).toEqual({ type: 'INCREMENT' });
  expect(increment.type).toBe('INCREMENT');
});

it('with payload', () => {
  const add = createAction('ADD', (type: 'ADD') => (amount: number) =>
    ({ type, payload: amount }),
  );

  expect(add(10)).toEqual({ type: 'ADD', payload: 10 });
  expect(add.type).toBe('ADD');
});

it('with payload and meta', () => {
  const notify = createAction('NOTIFY', (type: 'NOTIFY') =>
    (username: string, message: string) => ({
      type,
      payload: { message: `${username}: ${message}` },
      meta: { username, message },
    }),
  );

  expect(notify('Piotr', 'Hello!')).toEqual({
    type: 'NOTIFY',
    payload: { message: 'Piotr: Hello!' },
    meta: { username: 'Piotr', message: 'Hello!' },
  });
  expect(notify.type).toBe('NOTIFY');
});

createActions

(WIP)


MIT License

Copyright (c) 2017 Piotr Witek piotrek.witek@gmail.com (http://piotrwitek.github.io)

Keywords

FAQs

Package last updated on 15 Nov 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc