我正在使用 Redux 和 typesafe-actions,我想获得一个类型,我可以用它在我的减速器中对action
参数进行注释,以获得action.type
.
目前我的设置是这样的:
我使用 typesafe-actions 定义了我的操作:
export const increment = (amount: number) => action("INCREMENT", { amount });
export const decrement = (amount: number) => action("DECREMENT", { amount });
然后我可以像这样得到我想要的类型:
export type CounterActions = ReturnType<typeof increment | typeof decrement>;
然而,这并不是理想的可维护性,因为每次我添加一个新动作时,我都必须记住将它添加到 CounterActions 类型中。
所以我的想法是将我所有的动作创建器函数放在一个数组中:
export const actions = [
(amount: number) => action("INCREMENT", { amount }),
(amount: number) => action("DECREMENT", { amount })
]
然后type CounterActions
以某种方式“传播”数组。这是我卡住的地方,因为我无法正确使用语法。
有任何想法吗?
typesafe-actions 有一个名为ActionType的辅助类型,如果您有操作的映射对象,它将为您执行该联合。最简单的方法是在另一个文件中使用import *
. 例如:
import { ActionType } from 'typesafe-actions'
import * as counterActions from 'insert/filepath/here'
export type CounterActions = ActionType<typeof counterActions>;
在我的应用程序中,我们在 RootAction 的文件中执行此操作,该文件仅包含我们在整个应用程序中创建的所有操作。所以文件看起来像:
import * as fooActions from './foo/actions'
import * as barActions from './bar/actions'
// etc
export type RootAction =
ActionType<typeof fooActions>
| ActionType<typeof barActions>
// etc
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句