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:
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:
Yet, this solution comes at a cost: it screws all my auto-completion goodness... :( Is there a better way to handle Enums in FlowType?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With