(Seamless)ImmutableJS的getIn函数的类型检查参数

时间:2018-11-02 07:39:04

标签: javascript typescript immutable.js

我正在寻找向传递给getIn的参数添加类型安全性的方法。

给出以下状态形状:

interface State {
  isFetching: boolean;
  shippingZones: ShippingZone[];
}

及其初始状态:

const INITIAL_STATE = Immutable.from<State>({
  isFetching: false,
  shippingZones: []
});

和减速器:

export const ShippingZonesReducer = (
  state: ImmutableObjectMixin<State> = INITIAL_STATE,
  action: ShippingZonesAction
) => {
  switch (action.type) {
    case getType(Actions.syncShippingZones):
      return state.merge({ isFetching: true, shippingZones: [] });
    case getType(Actions.syncShippingZonesSuccess):
      return state.merge({
        isFetching: false,
        shippingZones: state
          .getIn(["shippingZones"]) // <---- how to add type safety to the argument of getIn?
          .concat(action.payload.map(jsonApiSimplifier))
      });
    case getType(Actions.syncShippingZonesFailure):
      return state.merge({ isFetching: false });
    default:
      return state;
  }
};

以当前形式,任何字符串都可以使用。如果我这样做:

getIn<keyof State>(["shippingZones"])

参数限于"isFetching" | "shippingZones",但弹出另一个问题:

enter image description here

我将所有源代码都包含在this gist中以获取更多上下文。谢谢您的时间!

0 个答案:

没有答案