soosap
soosap

Reputation: 1445

Handling Enums with 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

Upvotes: 8

Views: 378

Answers (1)

Jesse Hallett
Jesse Hallett

Reputation: 2007

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.

Upvotes: 2

Related Questions