Skip to content
Logo

T.opaque

The escape hatch, for values with no primitive of their own, such as a Map, a Set, a URL, or a class instance.

T.opaque(
  ({ random }) =>
    new Map([
      ["zone", Math.floor(random.next() * 5) + 1],
      ["days", Math.floor(random.next() * 10) + 1],
    ]),
);

The field's type is whatever the produce function returns, so T.opaque(({ random }) => new Map<string, number>()) needs no annotation.

produce receives { random, clock }: this schema's own stream, and "now" for this instance (see The clock is the entropy). Draw from random.next() and the field replays like every other primitive. If you use Math.random() instead, that field silently stops being reproducible.

T.always and T.enum can already hold any value, but T.always(someMap) returns the same object on every call and has no .as(). T.opaque is how you fabricate a new value each time, of a kind fabricator doesn't have.

T.opaque has no .as(), because produce already decides the whole value.

.as(produce) on the other primitives

Most primitives, including T.string, T.number, T.bigint, T.date, T.array, T.record, and T.boolean, have their own .as(produce). It replaces how that kind is generated with your own function:

T.string.as(() => crypto.randomUUID()).admits({ format: "uuid" });

These producers also receive { random, clock }, but they don't have to use it. They replace a kind that already generates its own values, so they're meant for one-off custom logic. If a producer ignores random, for example by calling crypto.randomUUID() as above, that field is not reproducible. To keep it reproducible, draw from random, or use the faker extension for realistic values. See Custom types for using .as() with a data library.

.admits({ format }) tells adapters like TypeBox what the strings are. Fabrication ignores it, and nothing checks that the producer's output matches. See .admits(...).