Samuel Vaillant
Samuel Vaillant

Reputation: 3847

Correctly type check reducer with Flow

I try to integrate Flow with a Redux codebase.
I'm pretty new to Flow but I already have played with TypeScript a little.

I want to be able to catch wrong action type inside the reducer.

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

I don't understand why Flow don't catch the error in this case. Flow infer the type property as a string but I set explicitly the type to be 'sample' | 'django'.

Did I miss something ?

Thanks!

Upvotes: 1

Views: 228

Answers (1)

lorefnon
lorefnon

Reputation: 13095

This seems like a bug in flow, but you can enforce a strict verification as follows:

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: '' };
  }
};

This gives:

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

Upvotes: 1

Related Questions