badrap/valita

Question: How to combine records and objects

arv opened this issue · 2 comments

arv commented

I'm not sure if this can be done with the existing APIs but I want to express something like the following TypeScript type:

type T = {
  x: number;
  [key: string]: string | number;
}

The best I could come up with is:

const schema = valita
  .record(valita.union(valita.string(), valita.number()))
  .chain(v =>
    valita.object({x: valita.number()}).try(v, {mode: 'passthrough'}),
  );
jviide commented

That can be done via the .rest() method:

const T = v
  .object({
    x: v.number(),
  })
  .rest(v.union(v.string(), v.number()));
jviide commented

I think that this question has been answered, so closing this 👍