Skip to content
Logo

T.recursive

A structure: a schema that refers to itself, such as a tree, a linked structure, or a generic JSON value.

const CategorySchema = T.recursive((self) =>
  T.object({
    name: T.string.whereby({ length: { min: 3, max: 20 } }),
    children: T.array(self).whereby({ length: { max: 3 } }),
  }),
).whereby({ depth: { max: 3 } });

body receives a self placeholder that means "recurse here". The value type, such as children being an array of categories in the example above, is inferred with no annotation, to any depth.

.whereby({ depth }) is required, because a recursive schema with no limit would never stop. At depth.max, fabrication uses a terminal schema instead of body. If you don't give one, it is built from body by turning every self that can stop into a stop:

A self that is required, such as an object field, a tuple slot, or the whole body, can't be turned into a stop. Then .whereby() throws, and you must give a terminal.

A terminal you give replaces the built one entirely, for example a custom leaf value or a JSON choice narrowed to one option. It doesn't patch the self spots inside body.

depth only has max, not min, on purpose. T.array, T.record, and T.string draw a count, so a min sets a floor on that draw. A recursive schema has no draw of its own. How deep a value goes depends on the kinds between self spots choosing not to recurse: an array drawing a length of 0, a choice picking a non-self option, or an optional field coming out absent. A real minimum would mean forcing those kinds' draws, which is a different feature.

At depth.max the recursion has to stop, so the built terminal empties every collection of self. If that collection says length.min: 1, an adapter would require at least one child at every level, and no finite tree passes that. So .whereby() throws UnsatisfiableRecursiveBoundError. Add .admits({ length: { min: 0 } }) to the collection: it still draws at least one child below the limit, but adapters no longer require one.

T.recursive((self) =>
  T.object({
    name: T.string.whereby({ length: { min: 3, max: 20 } }),
    children: T.array(self)
      .whereby({ length: { min: 1, max: 3 } })
      .admits({ length: { min: 0 } }),
  }),
).whereby({ depth: { max: 3 } });

size.min on a T.unique.record works the same way. A plain T.record never throws here, because adapters don't state a minimum for it. Neither does a collection under a presence wrapper such as T.optional(T.array(self)), because the terminal leaves the key out instead. A terminal you give yourself skips this check.

A body with two self fields, such as left and right, can produce 2^depth nodes. Keep depth.max small, around 3 or 4, unless you have a reason not to.