flow.js createSlice 访问通用密钥

时间:2020-12-30 04:57:33

标签: flowtype redux-toolkit

尝试为 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

1 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

c

(try)

我不知道你将如何获得有效载荷类型。