【问题标题】:flow.js createSlice access generic keyflow.js createSlice 访问通用键
【发布时间】:2021-04-06 16:16:21
【问题描述】:

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

【问题讨论】:

    标签: flowtype redux-toolkit


    【解决方案1】:

    我想你想要这样的东西:

    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
    

    (try)

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

    【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2023-02-16
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2018-06-18
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多