truefit
Every export of truefit, with its signature and doc comment: parse, VENDOR, string, number, boolean, literal and 112 more, plus 59 types.
import { parse, VENDOR, string, … } from 'truefit';Functions
assert
Throws unless value is what the schema describes. After it returns the value is typed, with no
new binding: this is check for code that has nothing to do on a no but stop.
function assert<T>(schema: Schema<T, unknown>, value: unknown): asserts value is T;| Parameter | Type |
|---|---|
schema | Schema<T, unknown> |
value | unknown |
Returns asserts value is T
parseAsync
parse, awaited: the value the schema produces from value, or every reason there is none,
having awaited every rule and every map that answers with a promise. A schema with none of
those parses to what parse gives.
function parseAsync<T, O>(schema: Schema<T, O>, value: unknown, options?: ParseOptions): Promise<Parsed<Out<T, O>>>;| Parameter | Type |
|---|---|
schema | Schema<T, O> |
value | unknown |
options (optional) | ParseOptions |
Returns Promise<Parsed<Out<T, O>>>
Constants
annotate
The same schema with a title, a description or examples on it. Nothing that validates reads them.
const annotate: <S extends AnySchema>(schema: S, meta: Meta) => S;any
const any: () => Schema<any>;array
const array: <T, O>(item: Schema<T, O>, options?: ArrayOptions) => Schema<T[], [O] extends [Same] ? Same : O[]>;bigint
A bigint. Its bounds are bigints, which a double cannot hold, so they are kept as given, in
value; a bound nobody set is an infinity, which every bigint is inside.
const bigint: (options?: BigintOptions) => Schema<bigint>;boolean
const boolean: (options?: BooleanOptions) => Schema<boolean>;brand
The same schema, with a brand on its type: a string branded 'UserId' is not assignable from a
plain string, so only a value that passed this schema can be used as one. Type only, as
readonly is: the node is the one it was given. The brand is on the input type too, which is
what a passing check narrows to.
const brand: <T, O, const B extends string | symbol>(schema: Schema<T, O>, _name: B) => Schema<T & Brand<B>, [O] extends [Same] ? Same : O & Brand<B>>;catchOf
The schema, and what parse reads in place of a value it refuses: fallback, or what a function
makes of the schema's issues. The fallback stands for an input, as a default does: it is held to
the schema and mapped by its transforms, so catchOf(transform(string(), Number), '0') hands out
0. check, issues and the input type still describe what the schema accepts: a fallback is a
thing parse does, as coercion is.
const catchOf: <T, O>(schema: Schema<T, O>, fallback: T | ((issues: readonly Issue[]) => T)) => Schema<T, Out<T, O>>;check
Whether value is what the schema describes. A type guard, so a passing check narrows.
const check: <T>(schema: Schema<T, unknown>, value: unknown) => value is T;codec
Two schemas and the two maps between them: parse reads a value with input, decodes it and
holds the result to output; encode does the same the other way. An ISO date string and a
Date, cents and a decimal string: one place says both directions. check describes what goes
in, which is the input schema alone, as it does for a pipe.
const codec: <I, IO, O, OO>(input: Schema<I, IO>, output: Schema<O, OO>, maps: CodecMaps<Out<I, IO>, Out<O, OO>>) => Codec<I, Out<O, OO>>;contains
The array schema, and at least one of its items is what match describes: JSON Schema's
contains, with min and max as its minContains and maxContains. The items are still each
held to the array's own item schema; match only counts.
const contains: <T extends readonly unknown[], O>(schema: Schema<T, O>, match: AnySchema, options?: ContainsOptions) => Schema<T, O>;custom
A type that is whatever a named predicate says it is (spec.md R10). The static type is the caller's to state.
const custom: <T>(name: string, test: Test) => Schema<T>;date
A Date that is a time: new Date(NaN) fails, and so does a string or a number that could be read as one.
const date: (options?: DateOptions) => Schema<Date>;discriminated
One object schema per value of tag, which is the case's key in cases and so a string. The
case is picked by that value, never by trying each.
const discriminated: <const C extends Cases>(tag: string, cases: C) => Schema<C[keyof C]["~type"], AnyOut<C[keyof C]>>;discriminatedBy
The same, for tags that are strings, numbers or booleans (parity.md decision 9): each case is an
object whose tag key is a literal, and that literal is its tag. A builder of its own, so that a
program whose tags are all strings does not carry the reading of them.
const discriminatedBy: <const C extends Schemas>(tag: string, cases: C) => Schema<C[number]["~type"], AnyOut<C[number]>>;encode
The other direction of a codec: a value of its output schema, held to that schema, encoded, and
the result held to the input schema. parse is the first direction, decoding.
const encode: <I, O>(schema: Codec<I, O>, value: unknown, options?: ParseOptions) => Parsed<I>;endsWith
The string schema, and the string ends with text.
const endsWith: <T extends string, O>(schema: Schema<T, O>, text: string) => Schema<T, O>;enumOf
const enumOf: <const T extends readonly (string | number)[]>(values: T) => Schema<T[number]>;exactOptional
Marks an object's field as one that may be absent and, when it is there, is not undefined
(optional reads undefined as absent, parity.md decision 2). A key the prototype holds counts
as there, as it does for a required field (decision 3).
const exactOptional: <T, O>(schema: Schema<T, O>) => OptionalSchema<T, O, T, never>;extend
The schema with more keys. One it already has is replaced where it stood, as a spread would.
const extend: <T, O, const S extends Shape>(schema: Schema<T, O>, shape: S) => Schema<Flat<Omit<T, keyof S> & ObjectOf<S>>, [O | S[keyof S]["~out"]] extends [Same] ? Same : Flat<Omit<Out<T, O>, keyof S> & ObjectFull<S>>>;func
Any function. What it takes and returns is not checked, since that cannot be known without calling it: typebox reads a function schema the same way, and zod, valibot and arktype wrap the function to check each call, which is another thing than validating a value.
const func: () => Schema<(...args: never[]) => unknown>;includes
The string schema, and the string has text somewhere in it.
const includes: <T extends string, O>(schema: Schema<T, O>, text: string) => Schema<T, O>;instanceOf
A value made by new of a class, or of one that extends it. The emitted code takes the class as a hook: text cannot hold it.
const instanceOf: <T>(type: abstract new (...args: never[]) => T) => Schema<T>;intersection
What every member accepts.
const intersection: <const T extends Schemas>(members: T) => Schema<AllOf<T>, AllOut<T>>;isAnything
const isAnything: () => boolean;isArray
const isArray: (schema: Node, value: unknown) => boolean;isBigint
const isBigint: (schema: Node, value: unknown) => boolean;isBoolean
const isBoolean: (_: Node, value: unknown) => boolean;isCase
const isCase: (schema: Node, value: unknown) => boolean;isClosed
An object whose unnamed keys are refused, or must each match the schema in item.
const isClosed: (schema: Node, value: unknown) => boolean;isContaining
An array the wrapped schema accepts, of whose items the schema in key accepts a number inside the bounds: JSON Schema's contains, minContains and maxContains.
const isContaining: (schema: Node, value: unknown) => boolean;isCounted
An object the wrapped schema accepts, with a number of keys inside the bounds.
const isCounted: (schema: Node, value: unknown) => boolean;isCustom
const isCustom: (schema: Node, value: unknown) => boolean;isDate
A Date whose time is a number: all four libraries with a date kind refuse new Date(NaN).
const isDate: (_: Node, value: unknown) => boolean;isEnding
const isEnding: (schema: Node, value: unknown) => boolean;isEvery
const isEvery: (schema: Node, value: unknown) => boolean;isHolding
const isHolding: (schema: Node, value: unknown) => boolean;isInstance
const isInstance: (schema: Node, value: unknown) => boolean;isLater
const isLater: (schema: Node, value: unknown) => boolean;isLiteral
const isLiteral: (schema: Node, value: unknown) => boolean;isMap
A Map whose every key is what the schema in key describes, and every value what the one in item does.
const isMap: (schema: Node, value: unknown) => boolean;isMapped
A transform describes what goes in: check asks the schema it wraps, and never runs the map.
The same holds of every schema that only adds something for parse or for issues to what it
wraps: a pipe's second schema, a function run before validation, a message, a rule that is awaited.
const isMapped: (schema: Node, value: unknown) => boolean;isMember
const isMember: (schema: Node, value: unknown) => boolean;isMultiple
Whether value is a multiple of step. The remainder is exact, so for a whole step it must be
zero. A fraction such as 0.1 has no exact double, and neither has 0.3, so there a value counts as a
multiple when it is within one rounding error of one: |value| × Number.EPSILON, which is the
most the two doubles can be off by together. So 0.3 and 0.1 + 0.2 are multiples of 0.1, as they are in the
decimal text of a JSON document, and 0.35 is not.
const isMultiple: (value: number, step: number) => boolean;isNan
NaN and no other number: the one a number schema refuses. Number.isNaN asks nothing of a value that is not a number.
const isNan: (_: Node, value: unknown) => boolean;isNot
A value the schema in key refuses.
const isNot: (schema: Node, value: unknown) => boolean;isNothing
const isNothing: () => boolean;isNullable
const isNullable: (schema: Node, value: unknown) => boolean;isNullish
const isNullish: (schema: Node, value: unknown) => boolean;isNumber
const isNumber: (schema: Node, value: unknown) => boolean;isObject
const isObject: (schema: Node, value: unknown) => boolean;isOne
A value exactly one member accepts: the second to accept it settles the answer.
const isOne: (schema: Node, value: unknown) => boolean;isRecord
for … in, here and in isClosed, because it allocates nothing. It also reads the enumerable
keys of the prototype, which is the reading parity.md decision 3 gives a named field.
const isRecord: (schema: Node, value: unknown) => boolean;isRefined
What the schema accepts, and of that what its rule allows. The rule is asked only about a value the schema accepted.
const isRefined: (schema: Node, value: unknown) => boolean;isSet
A Set of a size inside the bounds, whose every member is what the schema in item describes.
const isSet: (schema: Node, value: unknown) => boolean;isStarting
A string the wrapped schema accepts that starts with the text in value, ends with it, or has it somewhere inside.
const isStarting: (schema: Node, value: unknown) => boolean;isString
const isString: (schema: Node, value: unknown) => boolean;issues
The second pass (spec.md R6, R7): every reason value is not what the schema describes. Empty
exactly when check says yes.
const issues: <T>(schema: Schema<T, unknown>, value: unknown, options?: IssueOptions) => Issue[];isTemplate
A string a template describes. The template is read as a machine with no memory but the set of places it may stand at (Thompson's construction, 1968), one UTF-16 unit of the string at a time: the time is the length of the string times the size of the template, whatever the string. A regular expression made from the same template backtracks where two holes of open length follow each other, and this never does.
const isTemplate: (schema: Node, value: unknown) => boolean;isTuple
An array of exactly the schema's items (parity.md decision 12: a tuple is closed), or of those
and then any number that match the schema in item.
const isTuple: (schema: Node, value: unknown) => boolean;isTypeOf
const isTypeOf: (schema: Node, value: unknown) => boolean;isUnion
const isUnion: (schema: Node, value: unknown) => boolean;isUnique
An array the wrapped schema accepts, with no two items the same value: JSON Schema's uniqueItems.
const isUnique: (schema: Node, value: unknown) => boolean;keyCount
The number of keys an object has, read as a record's keys are read: for … in, which allocates nothing.
const keyCount: (value: object) => number;keyof
One of the schema's keys, as a string.
const keyof: <T>(schema: Schema<T, unknown>) => Schema<keyof T & string>;keysOf
The keys a JSON Pointer names (RFC 6901 §4), in order: an issue's path as an array. Given the
value the issue is about, a key that is an index into an array is a number, as zod writes a
path; without it, and under a Map or a Set, every key is a string.
const keysOf: (path: string, value?: unknown) => (string | number)[];lazy
A schema asked for when it is read, which is what lets one name itself or another that names it
back: const Tree: Schema<Tree> = object({ kids: array(lazy(() => Tree)) }).
const lazy: <T, O = Same>(get: () => Schema<T, O>) => Schema<T, O>;literal
const literal: <const T extends string | number | bigint | boolean | null | undefined>(value: T) => Schema<T>;lowercase
The string in lower case (String.prototype.toLowerCase, which follows no locale).
const lowercase: <T extends string, M extends string | Same = Same>(schema: Text<T, M>) => Schema<T, string>;mapOf
A Map whose keys match one schema and whose values match another.
const mapOf: <K, KO, V, VO>(key: Schema<K, KO>, value: Schema<V, VO>) => Schema<Map<K, V>, [KO | VO] extends [Same] ? Same : Map<Out<K, KO>, Out<V, VO>>>;matches
Whether a string is what a format names: its pattern, or else its test.
const matches: (rule: Rule, value: string) => boolean;matching
How many of the items a schema accepts.
const matching: (schema: Node, items: readonly unknown[]) => number;message
The schema, with your words for its issues: one message for every issue it reports, or one for
each keyword you name ({ type: '…', min: '…' }). The words replace the whole message, fix:
line included, and stand whatever a per-call message hook says: the schema's own words are the
more specific. Only the wrapped schema's own issues are reworded, those reported where it stands
and those about one of its keys (required, unknown, undefined, key, tag); a schema
inside it keeps its own.
const message: <T, O>(schema: Schema<T, O>, words: string | Readonly<Record<string, string>>) => Schema<T, O>;nan
NaN, and no other number: number() refuses it, as JSON does.
const nan: () => Schema<number>;nativeEnum
The values of a TypeScript enum. A numeric enum compiles to an object that also maps each
number back to its name ({ A: 0, 0: 'A' }), and those names are not values: 0 is accepted
and 'A' is not. A key is such a way back when its value is a name whose own value is that key;
to the type, it is a key that is a number.
const nativeEnum: <const T extends EnumObject>(members: T) => Schema<T[keyof T & string]>;never
Accepts no value.
const never: () => Schema<never>;normalize
The string in a Unicode normalization form (UAX #15, String.prototype.normalize): NFC unless another is named.
const normalize: <T extends string, M extends string | Same = Same>(schema: Text<T, M>, form?: NormalForm) => Schema<T, string>;not
Every value the schema refuses: JSON Schema's not. The type is unknown, since a type cannot
say "everything but"; narrow it with an intersection, intersection([string(), not(literal(''))]).
const not: (schema: AnySchema) => Schema<unknown>;nullable
T or null.
const nullable: <T, O>(schema: Schema<T, O>) => Schema<T | null, [O] extends [Same] ? Same : O | null>;nullish
T, null or undefined; as an object's field, the key may be absent.
const nullish: <T, O>(schema: Schema<T, O>) => OptionalSchema<T | null | undefined, [O] extends [Same] ? Same : O | null | undefined, T | null | undefined>;number
A finite number: NaN and the infinities fail, as they do in JSON.
const number: (options?: NumberOptions) => Schema<number>;object
const object: ObjectBuilder;omit
Every key but the named ones.
const omit: <T, O, const K extends keyof T & string>(schema: Schema<T, O>, keys: readonly K[]) => Schema<Omit<T, K>, [O] extends [Same] ? Same : Omit<O, K>>;oneOf
What exactly one member accepts: JSON Schema's oneOf, an exclusive or. A value two members
accept fails, which a union would let through. Every member is asked, so this costs more than a
union, which stops at the first that accepts; use it where two must not both hold.
const oneOf: <const T extends Schemas>(members: T) => Schema<T[number]["~type"], AnyOut<T[number]>>;optional
Marks an object's field as one that may be absent or undefined. It says that of the key, not of
the value: anywhere else (at the root, in an array, a tuple or a record) the schema is what it
was, so check(optional(string()), undefined) is false and the type says so. A value that may
itself be undefined is nullish, or a union with literal(undefined).
const optional: OptionalBuilder;parse
The value the schema produces from value, or every reason there is none. value is the input
itself unless a default, a stripped key, a coercion or a transform changed something, or copy
was asked for.
const parse: <T, O>(schema: Schema<T, O>, value: unknown, options?: ParseOptions) => Parsed<Out<T, O>>;partial
Every key optional: absent or undefined. A field keeps its default.
const partial: <T, O>(schema: Schema<T, O>) => Schema<Loose<T>, [O] extends [Same] ? Same : Loose<O>>;pick
Only the named keys. A name the schema does not have is no key of the result.
const pick: <T, O, const K extends keyof T & string>(schema: Schema<T, O>, keys: readonly K[]) => Schema<Pick<T, K>, [O] extends [Same] ? Same : Pick<O, K & keyof O>>;pipe
Two schemas in a row: what parse makes of the first is parsed by the second, and what the
second makes of it is the output. transform maps a value and trusts the result; a pipe holds
the result to a schema: pipe(transform(string(), Number), number({ min: 5 })).
const pipe: <T, M, U, R>(first: Schema<T, M>, second: Schema<U, R>) => Schema<T, Out<U, R>>;points
The number of code points in a string, which is what a length bound counts (parity.md decision 4:
JSON Schema's minLength and maxLength, zod and ajv). A surrogate pair is one; a surrogate
with no partner is one.
const points: (text: string) => number;preprocess
The schema, and a function parse runs on what arrived before anything is validated: a coercion
of your own. transform runs after validation, on a value of the schema's type; this runs
before it, on a value of any type, and what it returns is validated.
const preprocess: <T, O>(map: (value: unknown) => unknown, schema: Schema<T, O>) => Schema<T, O>;promise
A Promise. What it resolves to is not checked: that is only known later, and check answers
now. valibot, arktype and typebox read a promise schema the same way.
const promise: () => Schema<Promise<unknown>>;properties
The schema, held to a number of keys: JSON Schema's minProperties and maxProperties, for an
object or a record. The keys are counted as a record's are read, so an enumerable key of the
prototype counts (parity.md decision 3). A wrapper and not an option of object, so an object
that does not count its keys pays nothing for those that do.
const properties: <T extends object, O>(schema: Schema<T, O>, options: PropertiesOptions) => Schema<T, O>;readonly
The same schema, typed read-only, and marked readOnly for the JSON Schema and OpenAPI it is
written to: the value is the server's to set. Nothing is frozen: parse hands back the caller's
own value when nothing changed (parity.md decision 10), and freezing that would write to it. Of
the five libraries only zod freezes; valibot, arktype and typebox mark the type alone, as this does.
const readonly: <T, O>(schema: Schema<T, O>) => Schema<Readonly<T>, [O] extends [Same] ? Same : Readonly<O>>;record
An object with any keys, each value matching one schema. With an enum for key only its members
are keys, and none of them has to be there: recordOf is the record that needs every one.
const record: <V, O, K extends string = string>(value: Schema<V, O>, options?: RecordOptions<K>) => Schema<RecordOf<K, V>, [O] extends [Same] ? Same : RecordOf<K, O>>;recordOf
A record with exactly these keys, every one of them there, each value matching one schema: a closed object, written once.
const recordOf: <const K extends string, V, O>(keys: readonly K[], value: Schema<V, O>) => Schema<Record<K, V>, [O] extends [Same] ? Same : Record<K, O>>;refine
The schema, and a rule of your own on top of it (spec.md R10). The rule is handed what the schema accepted, so it can rely on the type; it returns true for a value it allows.
const refine: <T, O, const K extends keyof T & string = never>(schema: Schema<T, O>, test: (value: NoInfer<[K] extends [never] ? T : Pick<T, K>>) => boolean, options?: RefineOptions<K>) => Schema<T, O>;refineAsync
The schema, and a rule of your own that answers with a promise: a lookup, a call to a service.
parseAsync awaits it, on a value the whole schema accepted and before any transform runs, and
reports it under the keyword refine. parse refuses a schema that has one.
const refineAsync: <T, O>(schema: Schema<T, O>, test: (value: T) => Promise<boolean>, options?: RefineAsyncOptions) => Schema<T, O>;repeated
The index of the first item that is the same value as an earlier one, or -1. A value that is no
object is looked up in a set, so an array of strings and numbers is read in time proportional to
its length. An object is compared with every object before it: for an array of k objects that
is k × (k - 1) / 2 comparisons at worst, each as deep as the objects are alike.
const repeated: (items: readonly unknown[]) => number;required
Every key required: there, and not undefined.
const required: <T, O>(schema: Schema<T, O>) => Schema<Present<T>, [O] extends [Same] ? Same : Present<O>>;safeInteger
An integer every double can tell from its neighbours: from Number.MIN_SAFE_INTEGER to
Number.MAX_SAFE_INTEGER, so 2 ** 53 fails (parity.md decision 5: number({ int: true }) is any
integer-valued double). The safe range is put into the node's own two bounds, so check tests
nothing it did not test already, and a builder of its own, so number is no larger for it.
const safeInteger: (options?: Omit<NumberOptions, "int">) => Schema<number>;setOf
A Set whose members each match one schema; min and max bound its size.
const setOf: <T, O>(item: Schema<T, O>, options?: ArrayOptions) => Schema<Set<T>, [O] extends [Same] ? Same : Set<O>>;startsWith
The string schema, and the string starts with text: a prefix, without a regular expression of yours to escape.
const startsWith: <T extends string, O>(schema: Schema<T, O>, text: string) => Schema<T, O>;string
const string: (options?: StringOptions) => Schema<string>;symbol
const symbol: () => Schema<symbol>;template
A string made of text and holes, as TypeScript's template literal types make one:
template(['user-', number({ int: true })]) accepts user-7 and is typed `user-${number}`.
A hole holds a string, a number, a bigint, a boolean, or a literal, an enum, a union or a nullable
of those, with no bounds: what it matches is the text String writes for such a value. A number
is written as JSON writes one, so 1e+21 matches and 0x10 does not.
const template: <const P extends readonly (string | AnySchema)[]>(parts: P) => Schema<TemplateOf<P>>;transform
The schema, and a function that makes of what it accepts what parse hands out (spec.md R10).
check, issues and the input type describe what goes in; only parse runs the function, and
only on a value the whole schema accepted.
const transform: <T, M, R>(schema: Schema<T, M>, map: (value: Out<T, M>) => R) => Schema<T, R>;transformAsync
The schema, and a function that answers with a promise of what parseAsync hands out. It runs
as a transform does: after validation, on what the schema it wraps produced. parse refuses a
schema that has one.
const transformAsync: <T, M, R>(schema: Schema<T, M>, map: (value: Out<T, M>) => Promise<R>) => Schema<T, R>;trim
The string with the white space at its two ends removed (String.prototype.trim). Like every
transform it runs after validation: the schema describes the string as it arrives. To hold the
trimmed string to a schema, pipe(trim(string()), string({ min: 1 })).
const trim: <T extends string, M extends string | Same = Same>(schema: Text<T, M>) => Schema<T, string>;tuple
Exactly these items, in this order: one more or one fewer fails (parity.md decision 12). With
rest, any number of further items, each matching that schema.
const tuple: TupleBuilder;undefinedOf
Only undefined: the literal with no value. As an object's field it is a key that must be absent or undefined, so mark it optional.
const undefinedOf: () => Schema<undefined>;union
What any one member accepts. The members are tried in order, and the first to accept decides what parse returns.
const union: <const T extends Schemas>(members: T) => Schema<T[number]["~type"], AnyOut<T[number]>>;unique
The array schema, and no two of its items are the same value: JSON Schema's uniqueItems. Arrays
and plain objects are compared by what they hold, in any key order; a date by its time; NaN is
the same as NaN. Any other object is the same only as itself (check.ts, sameValue).
const unique: <T extends readonly unknown[], O>(schema: Schema<T, O>) => Schema<T, O>;unknown
Accepts every value. any is the same node with the type that switches checking off.
const unknown: () => Schema<unknown>;uppercase
The string in upper case (String.prototype.toUpperCase).
const uppercase: <T extends string, M extends string | Same = Same>(schema: Text<T, M>) => Schema<T, string>;voidOf
Only undefined, typed void: what a function that returns nothing returns. The same node as undefinedOf.
const voidOf: () => Schema<void>;Interfaces
ArrayOptions
interface ArrayOptions {
readonly min?: number;
readonly max?: number;
}BigintOptions
interface BigintOptions {
readonly min?: bigint;
readonly max?: bigint;
}BooleanOptions
interface BooleanOptions {
/** `parse` reads the boolean from the string `true` or `false`, exactly. `check` never does. */
readonly coerce?: boolean;
}Brand
What a brand adds to a type: a member no value has, named by the brand. Two brands on one type are both there.
interface Brand<B extends string | symbol> {
readonly '~brand': {
readonly [K in B]: true;
};
}Codec
A schema with two directions: parse decodes what arrives into the output, and encode turns an output back into what was sent.
interface Codec<I, O> extends Schema<I, O> {
readonly '~codec': true;
}CodecMaps
interface CodecMaps<I, O> {
/** From what the input schema accepted, to a value for the output schema. */
readonly decode: (value: I) => unknown;
/** From what the output schema accepted, to a value for the input schema. */
readonly encode: (value: O) => unknown;
}ContainsOptions
interface ContainsOptions {
/** The fewest items the schema has to accept: 1 unless another is given, and 0 makes the test always hold. */
readonly min?: number;
/** The most it may accept. */
readonly max?: number;
}DateOptions
interface DateOptions {
/**
* `parse` reads the date from a string that is, whole, an RFC 3339 date-time (`2020-01-01T00:00:00Z`,
* with any offset and any fraction) or full-date (`2020-01-01`, read as midnight UTC). `check` never does.
*/
readonly coerce?: boolean;
}DefaultedSchema
A field whose key may be absent going in, and is always there coming out of parse: an optional
with a default. Its output type is always written out, which is what tells an object that its
own output is not its input.
interface DefaultedSchema<T, O = T> extends Schema<T, O> {
readonly '~optional': T | undefined;
}Invalid
What assert throws: a TypeError whose message is the first issue, carrying every one of them.
interface Invalid extends TypeError {
readonly issues: readonly Issue[];
}Issue
interface Issue {
/** JSON Pointer to the value that failed; `''` is the root. */
readonly path: string;
/**
* What failed: `type`, `min`, `max`, `gt`, `lt`, `integer`, `multipleOf`, `pattern`, `format`,
* `literal`, `enum`, `required`, `unknown`, `key`, `length`, `tag`, `union`, `never`, `custom`,
* `date`, `instance`, `undefined`, `refine`, `minProperties`, `maxProperties`.
*/
readonly keyword: string;
/** What was expected and what arrived, ending in a `fix:` line; or the words a schema was given with `message`. */
readonly message: string;
}IssueOptions
interface IssueOptions {
/** Stop at the first issue. */
readonly first?: boolean;
/**
* The message for an issue, in your words or your language. It is asked about every issue of
* every schema, and what it returns is the whole message. Where it returns nothing the message
* stays as it was, with its `fix:` line: a map can cover the keywords it knows and leave the rest.
*/
readonly message?: (miss: Miss) => string | null | undefined;
}Meta
What a schema says about itself. Carried on the node and read back; validation ignores it.
interface Meta {
readonly title?: string;
readonly description?: string;
readonly examples?: readonly unknown[];
/** The value is the server's to set and a client's to leave out: OpenAPI's and JSON Schema's `readOnly`, which `readonly` sets. */
readonly readOnly?: boolean;
}Miss
One failed expectation at one place, before it is put into words: what a message is made from.
interface Miss {
readonly path: string;
readonly keyword: string;
/** What was expected, in English: the message reads "expected <expected>, got …". */
readonly expected: string;
/** The value that arrived. */
readonly got: unknown;
/** What to do about it, in English: the message ends "fix: <fix>". */
readonly fix: string;
}Node
interface Node {
readonly kind: Kind;
/** The kind's own check, put here by the builder so that a bundle carries only the kinds it builds. It captures nothing. */
readonly check: Check;
/** Length for a string or an array, value for a number, size for a set, the number of keys for a count of them. */
readonly min: number;
readonly max: number;
/** A number's exclusive bounds: the infinities when there are none. */
readonly above: number;
readonly below: number;
/** What a number must be a multiple of; zero when it need not be. */
readonly step: number;
readonly int: boolean;
/** `parse` reads the value from a string: a number from a JSON number, a boolean from `true` or `false`, a date from an RFC 3339 date or date-time. */
readonly coerce: boolean;
readonly pattern: RegExp | null;
/** A string's format, a custom type's predicate, or a refinement's rule: its name is what the rule expects. */
readonly rule: Rule | null;
/**
* The literal's value; a bigint's two bounds, lowest first; the name `typeof` gives the values of
* a `type` node; the class an `instance` node's values are instances of; a transform's map; the
* function a `preprocess` node runs first; the words of a `message` node, one string or one a keyword;
* the rule or the map that `parseAsync` awaits.
*/
readonly value: unknown;
/** The enum's members; on an object that closes or strips, its keys; on a refinement, the keys its rule reads. */
readonly values: ReadonlySet<unknown> | null;
/**
* The array's or the set's element, the record's or the map's value, the schema of an object's
* unnamed keys or of a tuple's items past its last, or what a schema that wraps another wraps: for
* a pipe, its first schema.
*/
readonly item: Node | null;
/** The record's or the map's key; a pipe's second schema. */
readonly key: Node | null;
/** The object's keys and, in the same order, their schemas; on a refinement, the path its issue is reported at. */
readonly keys: readonly string[] | null;
/** An object's fields, a tuple's items, or the members of a union or an intersection. */
readonly fields: readonly Node[] | null;
/** On an object's field: the key may be absent. `'exact'` is absent or a value, and never `undefined`. */
readonly optional: boolean | 'exact';
/** What `parse` puts where `undefined` arrived; `undefined` when there is none. */
readonly default: unknown;
readonly unknown: Unknown;
/** The discriminated union's key and its cases by that key's value: a string, a number or a boolean (parity.md decision 9). */
readonly tag: string | null;
readonly cases: ReadonlyMap<unknown, Node> | null;
/** A lazy node's schema, asked for when it is read: what lets a schema name itself. */
readonly get: (() => Node) | null;
readonly meta: Meta | null;
/** The kind's own reading for `issues` and `parse`; null for the eight kinds they read themselves. */
readonly own: Own | null;
}NumberOptions
interface NumberOptions {
readonly min?: number;
readonly max?: number;
/** Exclusive bounds: the bound itself fails. */
readonly gt?: number;
readonly lt?: number;
/** Above zero; `negative` is below zero. Zero is neither. */
readonly positive?: boolean;
readonly negative?: boolean;
/** See `isMultiple` in check.ts for what a multiple of a fraction is. */
readonly multipleOf?: number;
readonly int?: boolean;
/** `parse` reads the number from a string that is a JSON number. `check` never does. */
readonly coerce?: boolean;
}ObjectOptions
interface ObjectOptions<U> {
/**
* Keys the shape does not name: `'keep'` allows them and leaves them alone (the default, parity.md
* decision 1), `'strict'` refuses them, `'strip'` allows them and `parse` leaves them out of its
* output, and a schema is what each of their values must match.
*/
readonly unknown?: U;
}OptionalOptions
interface OptionalOptions<T> {
/**
* What `parse` puts where the value is absent or `undefined`. It stands for the input that was
* not there, so it is then read as an input is: coerced, filled and mapped by this schema where
* the schema does those things, and otherwise handed out as it is, uncopied. Freeze an object
* you give here. `check` and the input type still describe the input, where the key may be absent.
*/
readonly default?: T;
}OptionalSchema
A field whose key may be absent. F is what the key may hold when it is there, which for
optional is the schema's own type or undefined (parity.md decision 2), and G is what it
may hold coming out of parse beside the schema's output: undefined, or for an exact key nothing.
interface OptionalSchema<T, O = Same, F = T | undefined, G = undefined> extends Schema<T, O> {
readonly '~optional': F;
readonly '~absent': G;
}Own
What a kind brings for issues and for parse, when they do not know the kind themselves. They
know the eight kinds the design's first step named (string, number, boolean, literal, enum, array,
object, discriminated); every other kind's builder puts this on its node, as it puts check.
So issues and parse do not grow with the number of kinds, and a bundle carries the reading
of the kinds it builds.
interface Own {
readonly issues: Reader;
readonly fill: Filler;
}ParseOptions
interface ParseOptions extends IssueOptions {
/**
* Hand out a new object or array for every one the schema describes, changed or not, as zod and
* valibot always do. Without it the input itself comes back wherever nothing changed. What an
* `unknown` schema lets through is never copied: nothing describes it.
*/
readonly copy?: boolean;
}Pass
One walk of parse over a value. It makes two: one before check, and one after it when there is a transform to run.
interface Pass {
/** The walk after `check`: every value is one its schema accepted, and transforms run. */
late: boolean;
/** Every object and array the schema describes is rebuilt, changed or not. */
readonly copy: boolean;
/** Set by the first walk when it meets a transform: what makes the second worth making. */
met: boolean;
/** The way of `parse` into a schema inside this one, handed over as a walk's `visit` is. */
readonly fill: Filler;
/** Where the walk is: the keys from the root to the member being filled. */
readonly at: unknown[];
/** What the walk after `check` found wrong: the issues of a pipe's second schema. One of them fails the parse. */
readonly failed: Issue[];
/** `parse` itself and the options it was called with, for a schema that parses what another produced. */
readonly parse: (schema: Node, value: unknown, options: IssueOptions) => {
readonly ok: true;
readonly value: unknown;
} | {
readonly ok: false;
readonly issues: Issue[];
};
readonly options: IssueOptions;
/** Set by `parseAsync` alone: a schema that has to be awaited refuses a walk without it, and a rule that is awaited counts itself here. */
readonly wait?: {
rules: number;
};
}PropertiesOptions
interface PropertiesOptions {
/** The fewest and the most keys the object may have. */
readonly min?: number;
readonly max?: number;
}RecordOptions
interface RecordOptions<K extends string = string> {
/** What every key must be. A key is always a string, so this is a string schema or an enum of strings. */
readonly key?: Schema<K>;
}RefineAsyncOptions
interface RefineAsyncOptions {
/** Where under the value the issue is reported: the keys that lead there. The value itself when there are none. */
readonly path?: readonly (string | number)[];
/** What the rule expects, for the issue: it reads "expected <message>, got …". */
readonly message?: string;
}RefineOptions
interface RefineOptions<K extends string = string> {
/** Where under the value the issue is reported: the keys that lead there. The value itself when there are none. */
readonly path?: readonly (string | number)[];
/** What the rule expects, for the issue: it reads "expected <message>, got …". */
readonly message?: string;
/**
* The keys of the object that the rule reads. With them the rule runs whenever those fields are
* sound, whatever is wrong with the others, and is handed a value typed with those keys alone.
* Without them it runs only on a value that is sound all through.
*/
readonly uses?: readonly K[];
}Rule
A named rule, as data (spec.md R11): a string's format, or the whole of a custom type. One of pattern and test is set.
interface Rule {
readonly name: string;
readonly pattern: RegExp | null;
readonly test: Test | null;
}Same
What stands where a schema's output type would, when its output is its input. That is nearly every schema, and it is why the type of an object is worked out once and not twice: measured 2026-11-13 with TypeScript 6.0.3 on 200 copies of the order schema, carrying a second, equal type cost 725 instantiations a schema against 420, and this costs 461.
interface Same {
readonly '~same': never;
}Schema
A node that validates a T, and from which parse produces an O: Same unless a default
fills a key or a transform maps a value somewhere inside. The types live only in the type system.
interface Schema<T, O = Same> extends Node {
readonly '~type': T;
readonly '~out': O;
}StringOptions
interface StringOptions {
/** Code points, not UTF-16 units (parity.md decision 4). */
readonly min?: number;
readonly max?: number;
readonly length?: number;
readonly pattern?: RegExp;
readonly format?: Format;
}Walk
Where a walk of issues is, and where it writes. It also holds the two things of issues that a
reader calls, the way into a schema inside this one and the writing down of an issue, so that a
reader a node carries imports neither and a bundle without issues does not carry them.
interface Walk {
readonly found: Issue[];
readonly first: boolean;
readonly message: IssueOptions['message'];
readonly visit: Reader;
readonly add: (walk: Walk, miss: Miss) => void;
}Types
AllOf
What every one of the schemas validates at once.
type AllOf<T extends Schemas> = T extends readonly [Schema<infer First, unknown>, ...infer Rest extends Schemas] ? First & AllOf<Rest> : unknown;AllOut
type AllOut<T extends Schemas> = [T[number]['~out']] extends [Same] ? Same : AllFull<T>;AnyOut
The output type of a union of schemas, given as the union of their types.
type AnyOut<M extends AnySchema> = [M['~out']] extends [Same] ? Same : OutOf<M>;AnySchema
Any schema at all: the constraint for a function that takes one and does not care for its types.
type AnySchema = Schema<unknown, unknown>;Check
A schema is data (spec.md R1): every builder returns one frozen node, a kind and its constraints.
check, issues, parse, the code emitter and, later, the JSON Schema writer all read that node.
type Check = (schema: Node, value: unknown) => boolean;Filler
What parse runs for a kind: the value the schema makes of value, which is value itself when nothing changed.
type Filler = (schema: Node, value: unknown, pass: Pass) => unknown;Flat
type Flat<T> = {
[K in keyof T]: T[K];
};Format
A string format, as data (spec.md R11): a name and either a pattern or a test. Nothing is
registered anywhere; a format is a value a program keeps and hands to string({ format }).
type Format = {
readonly name: string;
readonly pattern: RegExp;
} | {
readonly name: string;
readonly test: (value: string) => boolean;
};Infer
What check accepts, and narrows to: the input. parse reads a little more where a schema asks
for coercion (a number from a string), which no type can say, so the input type is check's.
type Infer<S extends AnySchema> = S['~type'];InferInput
The same as Infer, under the name that pairs with InferOutput.
type InferInput<S extends AnySchema> = S['~type'];InferOutput
What parse produces: the input with every default filled and every transform applied.
type InferOutput<S extends AnySchema> = Out<S['~type'], S['~out']>;Kind
type Kind = 'string' | 'number' | 'boolean' | 'literal' | 'enum' | 'array' | 'object' | 'discriminated' | 'unknown' | 'never' | 'record' | 'tuple' | 'nullable' | 'nullish' | 'union' | 'intersection' | 'lazy' | 'custom' | 'bigint' | 'date' | 'type' | 'instance' | 'refine' | 'transform' | 'nan' | 'map' | 'set' | 'count' | 'message' | 'pipe' | 'preprocess' | 'refineAsync' | 'transformAsync' | 'template' | 'startsWith' | 'endsWith' | 'includes' | 'contains' | 'unique' | 'not' | 'oneOf' | 'catch' | 'codec';NormalForm
type NormalForm = 'NFC' | 'NFD' | 'NFKC' | 'NFKD';ObjectFull
An object as parse produces it, where that is not what went in: a key with a default is always there.
type ObjectFull<S extends Shape> = Flat<{
[K in Exclude<keyof S, AbsentKeys<S>>]: OutOf<S[K]>;
} & {
[K in AbsentKeys<S>]?: OutOf<S[K]> | (S[K] & MayStayAbsent)['~absent'];
}>;ObjectOf
type ObjectOf<S extends Shape> = Flat<{
[K in Exclude<keyof S, OptionalKeys<S>>]: S[K]['~type'];
} & {
[K in OptionalKeys<S>]?: (S[K] & MayBeAbsent)['~optional'];
}>;ObjectOut
An object's output type: Same when every field's is, and only otherwise worked out.
type ObjectOut<S extends Shape> = [S[keyof S]['~out']] extends [Same] ? Same : ObjectFull<S>;Out
The output type that a schema's two types stand for.
type Out<T, O> = [O] extends [Same] ? T : O;Parsed
The parse path: the value a schema's defaults, stripping and coercion produce, then check on
that value, then the schema's transforms on what check accepted. check itself stays a guard
that reads and never writes.
type Parsed<T> = {
readonly ok: true;
readonly value: T;
} | {
readonly ok: false;
readonly issues: Issue[];
};Reader
What issues runs for a kind: it writes down every reason got is not what the schema describes.
type Reader = (walk: Walk, schema: Node, got: unknown, path: string) => void;RecordOf
A record's type: any string as a key, or, when its keys are an enum, some of those and no other.
type RecordOf<K extends string, V> = string extends K ? Record<string, V> : {
[P in K]?: V;
};Shape
type Shape = Readonly<Record<string, AnySchema>>;Step
One step of a template's reading: a UTF-16 unit from low to high, or, when kind is 1, a way on to two other steps, each so many steps from this one.
type Step = readonly [kind: number, low: number, high: number];TemplateOf
The string a template's parts describe.
type TemplateOf<P extends readonly unknown[]> = P extends readonly [infer First, ...infer Rest] ? `${PieceOf<First>}${TemplateOf<Rest>}` : '';Test
A predicate a node names (spec.md R10). Beside check, get and a transform's map, it is the only kind of function a node may hold.
type Test = (value: unknown) => boolean;TupleFull
type TupleFull<T extends Schemas> = {
-readonly [K in keyof T]: OutOf<T[K]>;
};TupleOf
A tuple of schemas as the tuple of what they validate.
type TupleOf<T extends Schemas> = {
-readonly [K in keyof T]: T[K]['~type'];
};TupleOut
type TupleOut<T extends Schemas> = [T[number]['~out']] extends [Same] ? Same : TupleFull<T>;Unknown
What an object does with a key its shape does not name. strip is keep to check: only parse leaves the key out.
type Unknown = 'keep' | 'strict' | 'strip';Re-exported
Documented on the page of the entry point that declares them.
| Export | Kind | Documented in |
|---|---|---|
VENDOR | const | truefit/standard |
Validators from an API contract
Generate truefit validators and their TypeScript types from an OpenAPI or AsyncAPI contract with contractdiff's validator target, or read the contract's schemas at run time with fromJsonSchema.
truefit/emit
Every export of truefit/emit, with its signature and doc comment: emit, emitWith, typeOf, plus 4 types.