我正在使用 createSlice
连同 useReducer
.
我希望正确输入调度,即 React.Dispatch<ReducerActions>
.
如何从 createSlice
中提取操作类型?
以下不起作用,它解析为 AnyAction
...这是可以理解的,因为所有操作都通过所有 reducer 。
Dispatch<Parameters<typeof slice["reducer"]>[1]>
最佳答案
createSlice
将 Action 创建者作为键控对象存储在属性 actions
中。我们正在寻找的是所有 Action 创建者的返回类型的联合。我们将使用 mapped type得到这个。
type SliceActions<T> = {
[K in keyof T]: T[K] extends (...args: any[]) => infer A ? A : never;
}[keyof T]
type ActionTypes = SliceActions<typeof slice.actions>
我在此 Playground Link 中使用了文档中的计数器示例ActionTypes
的值评估为:
type ActionTypes = {
payload: number;
type: string;
} | {
payload: undefined;
type: string;
}
请注意,redux 工具包将其操作类型声明为 string
而不是特定的字符串文字。
关于typescript - 从 Redux Toolkit 的 createSlice 获取 Action 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64576133/