Skip to content
This repository was archived by the owner on Feb 16, 2021. It is now read-only.

How to type check enums in switch statements #52

Closed
gcanti opened this issue Jun 25, 2016 · 1 comment
Closed

How to type check enums in switch statements #52

gcanti opened this issue Jun 25, 2016 · 1 comment

Comments

@gcanti
Copy link
Owner

gcanti commented Jun 25, 2016

This doesn't raise errors (seems a bug in Flow facebook/flow#1835):

type Action = { type: 'A' } | { type: 'B' };

export function foo(action: Action): number {
  switch (action.type) {
    case 'AA' : // <= typo
      return 1
    case 'B' :
      return 2
  }
  return 0
}

Can be alleviated by introducing an auxiliary enum and using a type cast in each case:

type ActionType = 'A' | 'B';
type Action = { type: 'A' } | { type: 'B' };

export function foo(action: Action): number {
  switch (action.type) {
    case ('AA': ActionType) :
      return 1
    case ('B': ActionType) :
      return 2
  }
  return 0
}

raises

src/index.js:8
  8:     case ('AA': ActionType) :
               ^^^^ string. This type is incompatible with
  8:     case ('AA': ActionType) :
                     ^^^^^^^^^^ string enum

Cons

  • duplicated values in type ActionType
@gcanti
Copy link
Owner Author

gcanti commented Jun 26, 2016

Alas it doesn't work as expected, casting the enums seems to confuse Flow (v0.27.0) about object properties:

// @flow
type ActionType = 'A' | 'B';
type Action = { type: 'A', a: number } | { type: 'B', b: number };

export function foo(action: Action): number {
  switch (action.type) {
    case ('A': ActionType) :
      return action.a // <= throws property `a`. Property not found in object type
    case ('B': ActionType) :
      return action.b // <= throws property `b`. Property not found in object type
  }
  return 0
}

@gcanti gcanti closed this as completed Jul 15, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant