Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Enums with FlowType

Tags:

enums

flowtype

export type Size =
| 'small'
| 'medium'
| 'large'
| 'big'
| 'huge';

Defining the Size type like this gives me auto-completion in my IDE wherever I use it:

enter image description here

Yet, I also want to make use of these values inside of a component: let's say a dropdown menu w/ available size values.

In order to achieve that I am maintaining a sizes object out of which I can extract the Size FlowType by leveraging $Keys:

export const sizes = {
  small: 'small',
  medium: 'medium',
  large: 'large',
  big: 'big',
  huge: 'huge',
};

export type Size = $Keys<typeof sizes>;

It kind of works in that it points out invalid values for a prop: enter image description here

Yet, this solution comes at a cost: it screws all my auto-completion goodness... :( Is there a better way to handle Enums in FlowType?

enter image description here

like image 358
soosap Avatar asked Apr 14 '17 12:04

soosap


1 Answers

That's a neat use of $Keys!

I don't know of a better way to derive the Size type from an object. Maybe you could work in the other direction like this:

export type Size =
| 'small'
| 'medium'
| 'large'
| 'big'
| 'huge';

export const sizes: { [key: string]: Size } = {
  small: 'small',
  medium: 'medium',
  large: 'large',
  big: 'big',
  huge: 'huge',
};

or perhaps eliminate a bit of duplication this way:

export const sizes: { [key: string]: Size } = [
  'small',
  'medium',
  'large',
  'big',
  'huge'
].reduce((obj, s) => {
  obj[s] = s
  return obj
}, {})

Clearly that uses more boilerplate. But with the type constraint on sizes you at least get a check that prevents invalid strings from getting into the sizes object.

like image 145
Jesse Hallett Avatar answered Oct 15 '22 16:10

Jesse Hallett