oscklmO
Convex Community3y ago
9 replies
oscklm

v.union() prevents spreading array into function call

So i've become curious to as why v.union() requires the first 2 arguments to be directly passed, before being allowed to spread my mapped array?

What i'm trying to do is make this more validator more dynamic, by using my const of categories and generating a validator from the const:
// The manual approach i started with, which works
export const manuallyDefinedValidator = v.union(
  v.literal('DIY'),
  v.literal('kunst'),
  v.literal('musik'),
  v.literal('sport'),
  v.literal('science'),
  v.literal('natur'),
  v.literal('gaming'),
  v.literal('mad'),
  v.literal('tech'),
  v.literal('viden'),
  v.literal('nyheder'),
  v.literal('samfund'),
  v.literal('underholdning'),
);

My dynamic approach to generating the validator
// constants/categories.ts
export const categories = [
  'DIY',
  'kunst',
  'musik',
  'sport',
  'science',
  'natur',
  'gaming',
  'mad',
  'tech',
  'viden',
  'nyheder',
  'samfund',
  'underholdning',
] as const;

export type Category = (typeof categories)[number];

// A bit more dynamic IMO, but unsure if its overkill
export const categoryValidator = v.union(
  v.literal('underholdning'),
  v.literal('DIY'),
  ...categories.map((category) => v.literal(category)),
);


What i CANT do is this:
export const categoryValidator = v.union(...categories.map((category) => v.literal(category)));

More context...
Motivation for doing this, is that now i can just pass ´categories´ to my create video form, and render the categories in a select field, while also using the same categories const to generate my validator which i use in the createVideo mutation.
Was this page helpful?