Enum/Union to JS array value #370
-
Hey! I'm currently trying to write a schema which I can use as a source for input validation (API query string) and as a source for the possible values (as array). I want to define the possible values and if the input is one of those, it's valid. But it should be also possible to get a random value of that collection, so the schema is a single source of truth with all possible values. This is the schema I've tried to feed into // Works for randomizing; doesn't work for query string validation because it wants the whole array
const Colors = Type.Tuple([
Type.Literal('red'),
Type.Literal('blue')
])
// Works for validation; doesn't work for randomizing because the created JS code is not an array like ['red', 'blue']
const Colors = Type.Union([
Type.Literal('red'),
Type.Literal('blue')
]) Is this even possible, or do I still need to define the values manually? (Sorry for being lost, lol) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
@m4rvr Hi,
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 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 const ColorTuple = Type.Tuple(Color.anyOf) // ['red', 'green', 'blue'] Hope this helps! |
Beta Was this translation helpful? Give feedback.
@m4rvr Hi,
Type.Union
would be the correct way to define a set of possible color options.For getting all possible colors, you can remap the literal types inside the
Color
union type.Or optionally, remap a
Union
toTuple
if the tuple representation is required.Hope this helps!