使用Flow正确键入check reducer

时间:2017-05-15 16:56:05

标签: typescript redux flowtype

我尝试将Flow与Redux代码库集成 我对Flow很陌生,但我已经使用过TypeScript了。

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

jQuery(document).ready(function(){
  var alertForm = jQuery( "#sub_alert" );
  // Validation (Alert)
  alertForm.validate({
    rules: {
      alert_email: {
        required: true,
        email: true
      }
    },
    messages: {
      alert_email: {
        required: "Email is required",
        email: "Enter valid email"
      }
    }
  });
  jQuery(".sub_button").click(function(){
    if( alertForm.valid() ) {
      jQuery.post('<?php echo osc_base_url( true ); ?>', {email:jQuery("#alert_email").val(), userid:jQuery("#alert_userId").val(), alert:jQuery("#alert").val(), page:"ajax", action:"alerts"},
        function(data) {
          if(data == 1) { alert('<?php echo osc_esc_js( __( 'You have sucessfully subscribed to the alert', 'test' ) ); ?>'); }
          else if(data == -1) { alert('<?php echo osc_esc_js( __( 'Invalid email address', 'test' ) ); ?>'); }
          else { alert('<?php echo osc_esc_js( __( 'There was a problem with the alert', 'test' ) ); ?>'); 
        };
      });
      return false;
    }
  });
});

Exemple in Try Flow
Exemple in TypeScript Playground

我不明白为什么Flow不会在这种情况下发现错误。 Flow将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: '' }; } }; 属性推断为type,但我明确将类型设置为string

我错过了什么吗?

谢谢!

1 个答案:

答案 0 :(得分: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