【问题标题】:Correctly type check reducer with Flow使用 Flow 正确输入 check reducer
【发布时间】:2017-05-16 01:23:36
【问题描述】:

我尝试将 Flow 与 Redux 代码库集成。
我对 Flow 很陌生,但我已经玩过一些 TypeScript。

我希望能够在减速器中捕获错误的动作类型。

type Action = 
  | { type: 'sample' }
  | { type: 'django' }  
  ;

type State = {
  content: string,
};

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    // OK
    case 'sample':
      return { content: '' };

    // Should raise a type error, because the action type 
    // will never be equal to "error" 
    case 'error':
      return { content: '' };

    default:
      return { content: '' };
  }
};

Exemple in Try Flow
Exemple in TypeScript Playground

我不明白为什么 Flow 在这种情况下没有捕捉到错误。 Flow 将type 属性推断为string,但我将类型明确设置为'sample' | 'django'

我错过了什么吗?

谢谢!

【问题讨论】:

    标签: typescript redux flowtype


    【解决方案1】:

    这似乎是流程中的一个错误,但您可以强制执行严格的验证,如下所示:

    type ActionType = 'sample' | 'django'
    type Action = {type: ActionType}
    
    type State = {
      content: string,
    };
    
    const reducer = (state: State, action: Action): State => {
      const type:ActionType = action.type;
      switch (type) {
        // Should raise a type error, because the action type 
        // will never be equal to "error" 
        case 'error':
          return { content: '' };
        default:
          return { content: '' };
      }
    };
    

    这给出:

    13:     case 'error':
                 ^ string literal `error`. This type is incompatible with
    9:   const type:ActionType = action.type;
                    ^ string enum
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多