Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
ts-redux-actions
Advanced tools
Typesafe Redux Action Creators for TypeScript
This lib is a part of react-redux-typescript
library, which is a collection of valuable utilities commonly used across many TypeScript Projects.
main
module
jsnext:main
For NPM users
$ npm install --save ts-redux-actions
For Yarn users
$ yarn add ts-redux-actions
I wasn't satisfied with redux-actions with TypeScript because of separate payload & meta map functions which makes it not idiomatic when using with static typing.
What I mean here is it will break your function definition type inference and intellisense in returned "action creator" function (e.g. named arguments will be renamed to generic names like a1, a2, etc... and function arity with optional parameters will break your function signature entirely).
It will force you to do an extra effort for explicit type annotations and probably result in more boilerplate when trying to work around it.
Important note: Every function created by
createAction
has a convenientgetType
method for a reducer switch case scenarios like below to reduce common boilerplate (works to narrow "Discriminated Union" types, remember to add trailing!
to remove optional undefined type):
import { createAction, getType } from 'ts-redux-actions';
const increment = createAction('INCREMENT');
// const increment: (() => { type: "INCREMENT"; }) & { getType?(): "INCREMENT"; } << HERE
switch (action.type) {
// getter on every action creator function:
case increment.getType!():
return state + 1;
// alternative helper function for more "FP" style:
case getType(increment):
return state + 1;
default: return state;
}
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:
// 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 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',
(username: string, message?: string) => ({
type: 'NOTIFY',
payload: { message: `${username}: ${message}` },
})
)
// still all good!
// const notify2: (username: string, message?: string | undefined) => {
// type: "NOTIFY";
// payload: { message: string; };
// }
// 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',
(username: string, message?: string) => ({
type: 'NOTIFY',
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; };
// }
For more advanced usage scenarios please check use cases described in test specifications
get type literal from action creator
function getType(actionCreator: AC<T>): T
// AC<T> extends (...args: any[]) => { type: T }
Examples:
const increment = createAction('INCREMENT');
const type: 'INCREMENT' = getType(increment);
expect(type).toBe('INCREMENT');
// in reducer
switch (action.type) {
case getType(increment):
return state + 1;
default: return state;
}
creates action creator function with type helper
function createAction(typeString: T, creatorFunction?: CF): CF & { getType?(): T }
// CF extends (...args: any[]) => { type: T, payload?: P, meta?: M, error?: boolean }
Examples:
it('no payload', () => {
const increment = createAction('INCREMENT');
// same as:
// const increment = createAction('INCREMENT', () => ({ type: 'INCREMENT' }));
expect(increment()).toEqual({ type: 'INCREMENT' });
expect(increment.getType!()).toBe('INCREMENT');
});
it('with payload', () => {
const add = createAction('ADD',
(amount: number) => ({ type: 'ADD', payload: amount }),
);
expect(add(10)).toEqual({ type: 'ADD', payload: 10 });
expect(add.getType!()).toBe('ADD');
});
it('with payload and meta', () => {
const notify = createAction('NOTIFY',
(username: string, message: string) => ({
type: 'NOTIFY',
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.getType!()).toBe('NOTIFY');
});
(WIP)
MIT License
Copyright (c) 2017 Piotr Witek piotrek.witek@gmail.com (http://piotrwitek.github.io)
FAQs
Typesafe Redux Action Creators for TypeScript
The npm package ts-redux-actions receives a total of 9 weekly downloads. As such, ts-redux-actions popularity was classified as not popular.
We found that ts-redux-actions demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.