flowtype - flow.js createSlice 访问通用键
问题描述
尝试为 redux 工具包的 createSlice 编写声明。在创建一个声明时遇到问题,该声明接受一个对象,该对象使用一个返回对象键之一的函数读取它自己的键之一。
尝试了以下给出适当返回值的方法
declare function createSlice<a = {|
name: string,
initialState: Object,
reducers: {[reducerName: string]: () => void}, // can not do $PropertwyType<a> here because flow says a is not defined
|}>(a: a): {
actions: $ObjMap<$PropertyType<a, 'reducers'>, Function>,
};
const slice = createSlice({
initialState: {} = {},
reducers: {
exists: (state) => {
state.test = 1 // no flow error
}
}
})
slice.exists() //`no error
slice.doesNotExists // flow error.
上面正确地读取了动作,但是它没有正确地读取状态对象。所以我尝试了以下方法,它可以正确读取状态并在减速器中显示错误,但现在不再正确读取动作
declare function createSlice<a = {|
name: string,
initialState: Object,
reducers: {[reducerName: string]: () => void},
|}>(b: a & {
reducers: {[reducerName: string]: ($PropertyType<a, 'initialState'>) => void}
}): {
actions: $ObjMap<$PropertyType<a, 'reducers'>, Function>,
};
const slice = createSlice({
initialState: {} = {},
reducers: {
exists: (state) => {
state.test = 1 // flow error. Yay
}
}
})
slice.exists() //`no error
slice.doesNotExists // no error
解决方案
我想你想要这样的东西:
type AnyAction = { ... };
declare function createSlice<
State,
SliceName: string,
Reducers: { [reducerName: string]: ((State, AnyAction) => void | State) },
>(
{|
name: SliceName,
initialState: State,
reducers: Reducers,
|}
): {|
name: SliceName,
reducer: (State, AnyAction) => State,
reducers: Reducers,
actions: $ObjMapi<Reducers, Function>,
|};
const slice = createSlice({
name: 'counter',
initialState: { member: 'initial' },
reducers: {
exists: (state) => {
state.member = 'test';
state.nothing = 'beans'; // error
},
}
});
slice.actions.exists();
slice.actions.somethingElse(); // error
(尝试)
不过,我不知道您将如何获得有效载荷类型。
推荐阅读
- java - java BufferReader IO 异常:流已关闭
- java - 什么 gc 日志图是什么意思?
- php - 如何在 CodeIgniter 4 中多连接 MySql
- python - Python 的“all”函数的 C++ 等价物是什么?
- javascript - 如何分别删除每个 DOM 元素
- javascript - 如何使用不可见字符拆分文本以及如何获取它的 JS 表示?
- javascript - 为什么我的迷宫生成器没有检测到 p5.js 中是否已访问过某个单元格?
- r - 计算每行中的最大值是多少,然后将每个单元格除以该数字(在 R 中)
- python - 无法使用 Python 和 Beautiful Soup 从网站中提取日期值
- angular - 我应该如何在茉莉花中模拟 atob() 函数