Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Last active July 10, 2018 12:29
Show Gist options
  • Save karlhorky/4468bd3f6565ec2500c10367044ceb40 to your computer and use it in GitHub Desktop.
Save karlhorky/4468bd3f6565ec2500c10367044ceb40 to your computer and use it in GitHub Desktop.
How to create Enum module in Flow around version 0.72.0
// From https://github.com/facebook/flow/issues/627#issuecomment-389668600
// Pay special attention to:
// 1. We are casting each value to its own, as otherwise all of them would be strings
// 2. Freezing would be strictly required if we weren't casting each value to its
// own (1), but as we are, its becomes optional here from the flow point of view
const all = Object.freeze({
green: ("COLOR_GREEN": "COLOR_GREEN"),
red: ("COLOR_RED": "COLOR_RED"),
yellow: ("COLOR_YELLOW": "COLOR_YELLOW"),
});
type Color = $Values<typeof all>;
// optional but sometimes useful too
// we are casting to any as Object.values returns Array<mixed> and mixed can't be casted
const values: Array<Color> = Object.freeze((Object.values(all): any));
export {all as default, values};
export type {Color};
import colors, {values as colorValues} from "./colors";
import type {Color} from "./colors";
type SomethingRed = {
color: typeof colors.red
};
const thing: SomethingRed = {color: colors.red};
const color1: Color = colors.green;
const color2: Color = colors.red;
const color3: Color = colors.yellow;
console.log(colorValues); // ["COLOR_GREEN", "COLOR_RED", "COLOR_YELLOW"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment