Intersections

An intersection represents a logical AND relationship. You can apply this concept to your schemas with intersect and partially with merge. For simple object schemas I recommend merge and in all other cases intersect.

Intersect schema

The schema function intersect creates an AND relationship between any number of schemas that you pass as the first argument in the form of an array. To pass the validation, the validation of each schema passed must be successful. If this is the case, the schema merges the output of the individual schemas and returns the result. If the validation fails, the schema returns any issues that occurred.

import * as v from 'valibot';

// TypeScript
type Intersect = { foo: string } & { bar: number };

// Valibot
const IntersectSchema = v.intersect([
  v.object({ foo: v.string() }),
  v.object({ bar: v.number() }),
]);

Merge method

Technically, there is a big difference between intersect and merge. intersect is a schema function that executes the passed schemas during validation. In contrast, merge is a method that merges the entries of the given object schemas during initialization to create a new object schema.

As a result, merge usually has much better performance than intersect when validating unknown data. Also, subsequent object properties overwrite the previous ones. This is not the case with intersect, since the validation would fail if two properties with the same name are fundamentally different. However, this also means that the pipe and rest parameter of the passed object schemas must be ignored and redefined.

import * as v from 'valibot';

const ObjectSchema = v.merge([
  v.object({ foo: v.string(), baz: v.number() }),
  v.object({ bar: v.string(), baz: v.boolean() }),
]); // { foo: string; bar: string; baz: boolean }

In the previous code example, the baz property of the first object schema is overwritten by the baz property of the second object schema.

Contributors

Thanks to all the contributors who helped make this page better!

  • GitHub profile picture of fabian-hiller

Partners

Thanks to our partners who support the project ideally and financially.

Sponsors

Thanks to our GitHub sponsors who support the project financially.

  • GitHub profile picture of dailydotdev
  • GitHub profile picture of ivan-mihalic
  • GitHub profile picture of KATT
  • GitHub profile picture of osdiab
  • GitHub profile picture of Thanaen
  • GitHub profile picture of ruiaraujo012
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of caegdeveloper