Processing Enumerations with FlowType

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

A type definition Sizelike this gives me autocomplete in my IDE, wherever I use it:

enter image description here

However, I also want to use these values ​​inside the component: say, a drop-down menu with available size values.

To achieve this, I maintain an object size from which I can extract FlowType Size using $ Keys :

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

export type Size = $Keys<typeof sizes>;

It looks like it points to invalid values ​​for prop: enter image description here

However, this solution is expensive: it clicks on all of my autocompletion Q-factors ... :( Is there a better way to handle Enums in FlowType?

enter image description here

+6
1

$Keys!

Size . , :

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

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

, , :

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

, . sizes , , , sizes.

+1

Source: https://habr.com/ru/post/1016548/


All Articles