Skip to content

Enum/Union to JS array value #370

Answered by sinclairzx81
m4rvr asked this question in Q&A
Discussion options

You must be logged in to vote

@m4rvr Hi,

Type.Union would be the correct way to define a set of possible color options.

const Color = Type.Union([      // this will validate a string for the value 'red', 'green' or 'blue'
  Type.Literal('red'),
  Type.Literal('green'),
  Type.Literal('blue')
])

For getting all possible colors, you can remap the literal types inside the Color union type.

const colors = Color.anyOf.map(color => color.const)     // ['red', 'green', 'blue']

const random = colors[(Math.random() * colors.length)|0] // 'red' or 'green' or 'blue'

Or optionally, remap a Union to Tuple if the tuple representation is required.

const ColorTuple = Type.Tuple(Color.anyOf) // ['red', 'green', 'blue']

Hope this helps!

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@m4rvr
Comment options

@m4rvr
Comment options

@sinclairzx81
Comment options

Answer selected by m4rvr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants