首页 文章

流式打字减速机不会产生错误

提问于
浏览
1

我是flowtypes的新手,想要帮助输入这个减速器 .

// @flow

type State = {
  [id: string]: boolean
};

type Action = { type: 'SET_ID', id: number, someValue: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_ID':
      const { id, someValue } = action;
      return { [id]: someValue };
    default:
      (action: empty);
      return state;
  }
}

我将id作为数字和someValue作为字符串传递,但是状态id应该是字符串,someValue应该是boolean . Flow产生0个错误 . 有任何想法吗 ?

谢谢!

1 回答

  • 0

    我一直在使用flow一段时间,而不是专业人士,但我想我可能会帮忙 . 我在下面做的是虽然ID是一个变量,但我认为不需要为它分配一个键 - 它只是一个字符串 . 它只分配了一个变量,因为你将它传递给一个函数并使用它 - 所以它需要的只是一个字符串 . 这样,如果你传递一个数字,它现在应该抛出一个错误,以便你可以决定是否要先将数字转换为字符串,或者将初始项目更改为数字而不是状态类型中的字符串 .

    然后someValue是键(字符串)的值,它也应该是一个字符串而不是布尔值 .

    type State = {
      [string]: string
    };
    
    type Action = { type: 'SET_ID', id: number, someValue: string };
    
    function reducer(state: State, action: Action): State {
      switch (action.type) {
        case 'SET_ID':
          const { id, someValue } = action;
          return { [id.toString()]: someValue };
        default:
          (action: empty);
          return state;
      }
    }
    

    从reducer返回的数据的示例可能是这样的:

    {'1231413413324': 'my new value from the reducer'}
    

相关问题