Create a typebox schema where properties can be validated using values given at runtime

1.1k views Asked by At

Let's say we have a typescript interface:

interface RangedNumber: {
   value: number;
   minValue: number;
   maxValue: number;
}

I could generate this type from the following typebox schema:

const Schema = Type.Object({
  value: Type.Number(),
  minValue: Type.Number(),
  maxValue: Type.Number(),
});

type RangeNumber = Static<typeof Schema>;

Above schema would of course only validate the types of each property.

I know I can pass minimum and maximum to Type.Number():

value: Type.Number({ minimum: x, maximum: y }),

But I only know the values for min and max at runtime.

Anyone has ideas what the best approach would be to create such a custom schema using typebox so that:

  • The following sample should validate:
{
   value: 5,
   minValue: 0,
   maxValue: 10,
}
  • while the following sample should not validate:
{
   value: 200,
   minValue: 0,
   maxValue: 10,
}
0

There are 0 answers