首页 > 解决方案 > 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

标签: flowtyperedux-toolkit

解决方案


我想你想要这样的东西:

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

尝试

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


推荐阅读