# typesafe-actions
> 主要是学习翻译用的,目前翻译不完整
Typesafe utilities designed to reduce types verbosity
and complexity in Redux Architecture.
This library is part of the React & Redux TypeScript Guide ecosystem :book:
:star: Found it useful? Want more updates? Show your support by giving a :star:
:tada: Now updated to support TypeScript v3.5 :tada:
Features
- minimalistic - according to
size-snapshot
(Minified: 3.48 KB, Gzipped: 1.03 KB), check also on bundlephobia - secure and optimized - no external dependencies, bundled in 3 different formats (
cjs
,esm
andumd
for browser) with separate optimized bundles for dev & prod (same asreact
) - focus on quality - complete test-suite for an entire API surface containing regular runtime tests and extra type-tests to guarantee type soundness and to prevent regressions in the future TypeScript versions
- focus on performance - integrated performance benchmarks to guarantee that the computational complexity of types are in check and there are no slow-downs when your application grow
npm run benchmark:XXX
Codesandbox links
- Reference Todo-App implementation using
typesafe-actions
: Link - Starter to help reproduce bug reports: Link
Table of Contents
- Motivation
- Installation
- Compatibility Notes
- Contributing Guide
- Funding
- Tutorial
- API Docs
- Migration Guides
- Recipes
- Compare to others
- MIT License
Motivation
当时我准备把Redux和Typescript进行结合开发,我尝试使用redux-actions 来减少需要维护的代码和 action-creators 模板。不幸的是,由于错误的类型以及不完整的类型接口布遍了代码,所以结果并不理想(点击这里查看对照)
现存的解决方案不是太冗余就是使用 class 来解决(可读性差,而且需要new关键字😱)
所以我创建了typesafe-actions
来解决上述的痛点
核心设计方案是设计一个使用TypeScript中type-inference💪力量的API来举起“可维护的负担”的类型注释。另外,我希望使他“看起来或者感觉起来”都尽可能的接近我们所习惯的JavaScript❤️,所以我不想写太多多余的注解来给代码带来过多的噪点。
安装
1 |
|
兼容性注意
TypeScript support
- `typesafe-actions@1.X.X` - minimal TS v2.7
- `typesafe-actions@2.X.X` - minimal TS v2.9
- `typesafe-actions@3.X.X` - minimal TS v3.2
- `typesafe-actions@4.X.X` - minimal TS v3.2
浏览器支持情况
兼容所有主流浏览器。
旧的浏览器的支持情况:IE <= 11 ,某些手机浏览器你需要提供下列的扩展库
Recommended polyfill for IE
To provide the best compatibility please include a popular polyfill package in your application, such as core-js
or react-app-polyfill
for create-react-app
.
Please check the React
guidelines to learn how to do that: LINK
A polyfill fo IE11 is included in our /codesandbox
application.
Contributing Guide
We are open for contributions. If you’re planning to contribute please make sure to read the contributing guide: CONTRIBUTING.md
Funding
Typesafe-Actions is an independent open-source project created by people investing their free time for the benefit of our community.
If you are using Typesafe-Actions please consider donating as this will guarantee the project will be updated and maintained in the long run.
Issues can be funded by anyone interested in them being resolved. Reward will be transparently distributed to the contributor handling the task through the IssueHunt platform.
Tutorial
为了展示使用了这个库type-safety后的灵活性和强大,让我们使用Redux结构来构建一个最常见的应用——经典的 todo-app 应用
注意
请确保你以具备以下的知识点以便能顺利的完成教程: Type Inference, Control flow analysis, Tagged union types, Generics and Advanced Types.
常量
RECOMMENDATION:
When usingtypesafe-actions
in your project you won’t need to export and reuse string constants. It’s because action-creators created by this library have static property with action type that you can easily access using actions-helpers and then use it in reducers, epics, sagas, and basically any other place. This will simplify your codebase and remove some boilerplate code associated with the usage of string constants. Check our/codesandbox
application to learn some best-practices to create such codebase.
使用字符串常量时的Typescript局限 - 当使用字符创常量作为action
的type时, 请确保使用简单易懂的字符串常量. 限制来自原 type-system, 因为所有的动态字符创操作(比如:字符串连接,字符串模板以及作为映射的对象)会扩大这个类型成为着急类,String
。结果就是破坏了action的上下文意思。
1 |
|
Actions
不同的项目有不同的需求,不同的团队有不同的约定,这就是为什么我认为typesafe-actions
设计的为什么需要设计的灵活。这里提供三种常用的不同方式让你选择,所以你可以选择最适合你团队的。
1. Basic actions
action
和 createAction
是两个使用预设好的属性 ({ type, payload, meta })来创建 actions的创建者. 这使他们简洁而又自以为是。
重要的属性是生成的action-creator将具有可变数量的参数并保留其语义名称(id,title,amount等)。
这两个创建者是非常像的,唯一不同的是 action
不能和 action-helpers
一起使用。
1 |
|
2. FSA compliant actions
This style is aligned with Flux Standard Action, so your action object shape is constrained to ({ type, payload, meta, error })
. It is using generic type arguments for meta
and payload
to simplify creation of type-safe action-creators.
It is important to notice that in the resulting action-creator arguments are also constrained to the predefined: (payload, meta)
, making it the most opinionated creator.
TIP: This creator is the most compatible with
redux-actions
in case you are migrating.
1 |
|
3. Custom actions (non-standard use-cases)
This approach will give us the most flexibility of all creators, providing a variadic number of named parameters and custom properties on action object to fit all the custom use-cases.
1 |
|
TIP: For more examples please check the API Docs.
RECOMMENDATION
Common approach is to create aRootAction
in the central point of your redux store - it will represent all possible action types in your application. You can even merge it with third-party action types as shown below to make your model complete.
1 |
|
Action Helpers
现在我想展时以下action-helpers以及解释一下他的用例。我们将要实现一个没有副作用的当用户成功添加新数据时展现成功的提示。
主要注意以下,所有的这些helpers都是扮演者类型守护者,所以他们全部都是小标签组成的唯一Type(RootAction
)来指定我们想要的action类型
使用action-creators
来替代类型常量
我们可以用action-creators来替代类型常量来匹配reduces里指定的action以及epics用例。通过为包含类型字符的action-creator实例添加静态属性来使用
最常用的命令就是getType
,他常用于常规的reducer中的switch cases:
1 |
|
Then we have the isActionOf
helper which accept action-creator as first parameter matching actions with corresponding type passed as second parameter (it’s a curried function).
1 |
|
Using regular type-constants
Alternatively if your team prefers to use regular type-constants you can still do that.
We have an equivalent helper (isOfType
) which accept type-constants as parameter providing the same functionality.
1 |
|
TIP: you can use action-helpers with other types of conditional statements.
1 |
|
Reducers
Extending internal types to enable type-free syntax with createReducer
We can extend internal types of typesafe-actions
module with RootAction
definition of our application so that you don’t need to pass generic type arguments with createReducer
API:
1 |
|
Using createReducer API with type-free syntax
We can prevent a lot of boilerplate code and type errors using this powerfull and completely typesafe API.
Using handleAction chain API:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20// using action-creators
const counterReducer = createReducer(0)
// state and action type is automatically inferred and return type is validated to be exact type
.handleAction(add, (state, action) => state + action.payload)
.handleAction(add, ... // <= error is shown on duplicated or invalid actions
.handleAction(increment, (state, _) => state + 1)
.handleAction(... // <= error is shown when all actions are handled
// or handle multiple actions using array
.handleAction([add, increment], (state, action) =>
state + (action.type === 'ADD' ? action.payload : 1)
);
// all the same scenarios are working when using type-constants
const counterReducer = createReducer(0)
.handleAction('ADD', (state, action) => state + action.payload)
.handleAction('INCREMENT', (state, _) => state + 1);
counterReducer(0, add(4)); // => 4
counterReducer(0, increment()); // => 1
Alternative usage with regular switch reducer
First we need to start by generating a tagged union type of actions (TodosAction
). It’s very easy to do by using ActionType
type-helper.
1 |
|
Now we define a regular reducer function by annotating state
and action
arguments with their respective types (TodosAction
for action type).
1 |
|
Now in the switch cases we can use the type
property of action to narrowing the union type of TodosAction
to an action that is corresponding to that type.
1 |
|
Async-Flows
With redux-observable
epics
To handle an async-flow of http request lets implement an epic
. The epic
will call a remote API using an injected todosApi
client, which will return a Promise that we’ll need to handle by using three different actions that correspond to triggering, success and failure.
To help us simplify the creation process of necessary action-creators, we’ll use createAsyncAction
function providing us with a nice common interface object { request: ... , success: ... , failure: ... }
that will nicely fit with the functional API of RxJS
.
This will mitigate redux verbosity and greatly reduce the maintenance cost of type annotations for actions and action-creators that would otherwise be written explicitly.
1 |
|
With redux-saga
sagas
With sagas it’s not possible to achieve the same degree of type-safety as with epics because of limitations coming from redux-saga
API design.
Typescript issues:
- Typescript does not currently infer types resulting from a
yield
statement so you have to manually assert the type e.g.const response: Todo[] = yield call(...
Here is the latest recommendation although it’s not fully optimal. If you managed to cook something better, please open an issue to share your finding with us.
1 |
|
API Docs
Action-Creators API
action
Simple action factory function to simplify creation of type-safe actions.
WARNING:
This approach will NOT WORK with action-helpers (such asgetType
andisActionOf
) because it is creating action objects while all the other creator functions are returning enhanced action-creators.
1 |
|
Examples:
> Advanced Usage Examples
1 |
|
TIP: Starting from TypeScript v3.4 you can achieve similar results using new
as const
operator.
1 |
|
createAction
Create an enhanced action-creator with unlimited number of arguments.
- Resulting action-creator will preserve semantic names of their arguments
(id, title, amount, etc...)
. - Returned action object have predefined properties
({ type, payload, meta })
1 |
|
TIP: Injected
actionCallback
argument is similar toaction
API but doesn’t need the “type” parameter
Examples:
> Advanced Usage Examples
1 |
|
createStandardAction
Create an enhanced action-creator compatible with Flux Standard Action to reduce boilerplate and enforce convention.
- Resulting action-creator have predefined arguments
(payload, meta)
- Returned action object have predefined properties
({ type, payload, meta, error })
- But it also contains a
.map()
method that allow to map(payload, meta)
arguments to a custom action object({ customProp1, customProp2, ...customPropN })
1 |
|
TIP: Using
undefined
as generic type parameter you can make the action-creator function require NO parameters.
Examples:
> Advanced Usage Examples
1 |
|
createCustomAction
Create an enhanced action-creator with unlimited number of arguments and custom properties on action object.
- Resulting action-creator will preserve semantic names of their arguments
(id, title, amount, etc...)
. - Returned action object have custom properties
({ type, customProp1, customProp2, ...customPropN })
1 |
|
Examples:
> Advanced Usage Examples
1 |
|
createAsyncAction
Create an object containing three enhanced action-creators to simplify handling of async flows (e.g. network request - request/success/failure).
1 |
|
AsyncActionCreator
1 |
|
TIP: Using
undefined
as generic type parameter you can make the action-creator function require NO parameters.
Examples:
> Advanced Usage Examples
1 |
|
Reducer-Creators API
createReducer
Create a typesafe reducer
1 |
|
Examples:
> Advanced Usage Examples
TIP: You can use reducer API with a type-free syntax by Extending internal types, otherwise you’ll have to pass generic type arguments like in below examples
1
2
3
4
5
// type-free syntax doesn't require generic type arguments
const counterReducer = createReducer(0, {
ADD: (state, action) => state + action.payload,
[getType(increment)]: (state, _) => state + 1,
})
Using type-constants as keys in the object map:1
2
3
4
5
6
7
8
9
10
11
12import { createReducer, getType } from 'typesafe-actions'
type State = number;
type Action = { type: 'ADD', payload: number } | { type: 'INCREMENT' };
const counterReducer = createReducer<State, Action>(0, {
ADD: (state, action) => state + action.payload,
[getType(increment)]: (state, _) => state + 1,
})
counterReducer(0, add(4)); // => 4
counterReducer(0, increment()); // => 1
Using handleAction chain API:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17// using action-creators
const counterReducer = createReducer<State, Action>(0)
.handleAction(add, (state, action) => state + action.payload)
.handleAction(increment, (state, _) => state + 1)
// handle multiple actions by using array
.handleAction([add, increment], (state, action) =>
state + (action.type === 'ADD' ? action.payload : 1)
);
// all the same scenarios are working when using type-constants
const counterReducer = createReducer<State, Action>(0)
.handleAction('ADD', (state, action) => state + action.payload)
.handleAction('INCREMENT', (state, _) => state + 1);
counterReducer(0, add(4)); // => 4
counterReducer(0, increment()); // => 1
Extend or compose various reducers together - every operation is completely typesafe:1
2
3
4
5
6
7
8
9const newCounterReducer = createReducer<State, Action>(0)
.handleAction('SUBTRACT', (state, action) => state - action.payload)
.handleAction('DECREMENT', (state, _) => state - 1);
const bigReducer = createReducer<State, Action>(0, {
...counterReducer.handlers, // typesafe
...newCounterReducer.handlers, // typesafe
SUBTRACT: decrementReducer.handlers.DECREMENT, // <= error, wrong type
})
Action-Helpers API
getType
Get the type property value (narrowed to literal type) of given enhanced action-creator.
1 |
|
Examples:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import { getType, createStandardAction } from 'typesafe-actions';
const add = createStandardAction('ADD')<number>();
// In switch reducer
switch (action.type) {
case getType(add):
// action type is { type: "ADD"; payload: number; }
return state + action.payload;
default:
return state;
}
// or with conditional statements
if (action.type === getType(add)) {
// action type is { type: "ADD"; payload: number; }
}
isActionOf
Check if action is an instance of given enhanced action-creator(s)
(it will narrow action type to a type of given action-creator(s))
WARNING: Regular action creators and action will not work with this helper
1 |
|
Examples:
> Advanced Usage Examples
1 |
|
isOfType
Check if action type property is equal given type-constant(s)
(it will narrow action type to a type of given action-creator(s))
1 |
|
Examples:
> Advanced Usage Examples
1 |
|
Type-Helpers API
Below helper functions are very flexible generalizations, works great with nested structures and will cover numerous different use-cases.
ActionType
Powerful type-helper that will infer union type from import * as … or action-creator map object.
1 |
|
StateType
Powerful type helper that will infer state object type from reducer function and nested/combined reducers.
WARNING: working with redux@4+ types
1 |
|
Migration Guides
v3.x.x
to v4.x.x
From v4.x.x
all action creators will use undefined
instead of void
as a generic type parameter to make the action-creator function require NO parameters.1
2
3
4
5
6
7
8
9const increment = createStandardAction('INCREMENT')<undefined>();
increment(); // <= no parameters required
const fetchUsersAsync = createAsyncAction(
'FETCH_USERS_REQUEST',
'FETCH_USERS_SUCCESS',
'FETCH_USERS_FAILURE'
)<undefined, User[], Error>();
fetchUsersAsync.request(); // <= no parameters required
v2.x.x
to v3.x.x
v3.x.x
API is backward compatible with v2.x.x
. You’ll only need to update typescript dependency to > v3.1
.
v1.x.x
to v2.x.x
In v2 we provide a createActionDeprecated
function compatible with v1 API to help with incremental migration.
1 |
|
Migrating from redux-actions
to typesafe-actions
- createAction(s)
1 |
|
- handleAction(s)
1 |
|
TIP: If migrating from JS -> TS, you can swap out action-creators from
redux-actions
with action-creators fromtypesafe-actions
in yourhandleActions
handlers. This works because the action-creators fromtypesafe-actions
provide the sametoString
method implementation used byredux-actions
to match actions to the correct reducer.
- combineActions
Not needed because each function in the API accept single value or array of values for action types or action creators.
Recipes
Restrict Meta type in action
creator
Using this recipe you can create an action creator with restricted Meta type with exact object shape.
1 |
|
Compare to others
Here you can find out a detailed comparison of typesafe-actions
to other solutions.
redux-actions
Lets compare the 3 most common variants of action-creators (with type only, with payload and with payload + meta)
Note: tested with “@types/redux-actions”: “2.2.3”
- with type only (no payload)
redux-actions
1 |
|
with
redux-actions
you can notice the redundant nullablepayload
property and literal type oftype
property is lost (discrimination of union type would not be possible)
typesafe-actions
1 |
|
with
typesafe-actions
there is no excess nullable types and no excess properties and the action “type” property is containing a literal type
- with payload
redux-actions
1 |
|
first the optional
message
parameter is lost,username
semantic argument name is changed to some generict1
,type
property is widened once again andpayload
is nullable because of broken inference
typesafe-actions
1 |
|
typesafe-actions
infer very precise resulting type, notice working optional parameters and semantic argument names are preserved which is really important for great intellisense experience
- with payload and meta
redux-actions
1 |
|
this time we got a completely broken arguments arity with no type-safety because of
any
type with all the earlier issues
typesafe-actions
1 |
|
typesafe-actions
never fail toany
type, even with this advanced scenario all types are correct and provide complete type-safety and excellent developer experience
MIT License
Copyright (c) 2017 Piotr Witek piotrek.witek@gmail.com (http://piotrwitek.github.io)