API reference@evolu/common › Type

Runtime validation with precise TypeScript types and structured errors.

Evolu Type is a pure, synchronous codec for defining semantic domains. It partially decodes an Input into an Output and totally encodes every valid Output into a CanonicalInput. Types can validate, refine, transform, and compose without losing the contracts TypeScript can express.

Decoding failures are explicit Result values, and their structured errors preserve the exact error types each Type can return.

Evolu Type is designed to make correct code the easiest code to write:

  • Predefined constraints add a Brand to their Output.
  • Invalid declarations produce readable CompileTimeError types when the compiler can detect them.
  • Evolu Type uses runtime assertions to detect developer errors that TypeScript cannot express, such as excess properties and sparse arrays.
  • Typed from boundaries allow connecting value producers to domain fields through their exact TypeScript types, so incompatible contract changes are compile-time errors rather than runtime validation errors.
  • Lawful codecs compose without creating unencodable values: every valid Output has a canonical Input representation and round-trips to the same semantic value.
  • Type-safe localization infers the required error formatters from selected Types, so missing validation messages are compile-time errors.

Correctness is especially important for local-first data: application authors cannot inspect or repair a user's data.

Evolu Type is optimized for small real-world bundles: composed Types share runtime code, while unused validators and formatters are tree-shaken. It could be smaller with less descriptive assertion messages, but Evolu favors actionable diagnostics over micro-optimizing isolated Types.

Predefined Types use the names of corresponding JavaScript built-ins. When a Type shadows one, access the JavaScript built-in through globalThis, such as globalThis.String or globalThis.Date.

Evolu Type supports Standard Schema and requires TypeScript 7+ with exactOptionalPropertyTypes enabled.

Examples

Define a domain object with a custom Age Type, then validate unknown input:

import {
  assertEqual,
  Data,
  assertErr,
  assertOk,
  assertType,
  Number,
  NonEmptyTrimmedString100,
  brand,
  finite,
  int,
  lessThan,
  nonNaN,
  nonNegative,
  object,
  type Brand,
  type InferErrors,
  type InferType,
} from "@evolu/common";

// Age and its parent Types are predefined by Evolu. They are reconstructed
// here to reveal every constraint behind a seemingly simple domain value.
const NonNaNNumber = nonNaN(Number);
const FiniteNumber = finite(NonNaNNumber);
const Int = int(FiniteNumber);
const NonNegativeInt = nonNegative(Int);

const Age = brand("Age", lessThan(200)(NonNegativeInt));
type Age = typeof Age.Output;

assertType<
  number &
    Brand<"NonNaN"> &
    Brand<"Finite"> &
    Brand<"Int"> &
    Brand<"NonNegative"> &
    Brand<"LessThan200"> &
    Brand<"Age">,
  Age
>();

const User = object({
  name: NonEmptyTrimmedString100,
  age: Age,
});
interface User extends InferType<typeof User> {}

const value: unknown = { name: "Ada", age: 37 };
const user = User.fromUnknown(value);

assertOk(user, { name: "Ada", age: 37 });
assertType<typeof User.Output, typeof user.value>();

const invalidUser = User.fromUnknown({ name: "Ada", age: 37.5 });

assertErr(invalidUser);
// InferErrors includes every structured error User.fromUnknown can return.
assertType<InferErrors<typeof User>, typeof invalidUser.error>();
assertType(Data, invalidUser.error);
assertEqual(invalidUser.error, {
  type: "Object",
  reason: {
    kind: "Properties",
    errors: {
      age: { type: "Int", value: 37.5 },
    },
  },
});

A Type can format its structured errors into user-facing messages:

import { assertEqual, assertType, Data, assertErr, Age } from "@evolu/common";

const age = Age.fromUnknown(37.5);

assertErr(age);
assertType(Data, age.error);
assertEqual(age.error, { type: "Int", value: 37.5 });
assertEqual(
  Age.formatError(age.error),
  "The value 37.5 must be a safe integer.",
);

Use localizeTypes to derive Types with localized messages without changing validation behavior.

One of Evolu Type's strongest features is typed from boundaries. A value producer, such as a form input, carries the precise constraints it guarantees, and TypeScript checks them against the consuming domain field. Unlike validation from unknown or string, this checks the contract between the producer and consumer, not merely whether the current value passes:

import {
  assertOk,
  assertType,
  NonEmptyTrimmedString100,
  NonEmptyTrimmedString1000,
  object,
  trim,
  type MaxLengthError,
  type MinLengthError,
  type Result,
  type TrimmedString,
} from "@evolu/common";

const Todo = object({ title: NonEmptyTrimmedString100 });

// This is type-checked: Todo.from expects NonEmptyTrimmedString100.
const title = NonEmptyTrimmedString100.orThrow("Buy milk");
assertOk(Todo.from({ title }), { title });

// Imagine the UI input component is changed to allow longer titles.
// TypeScript rejects the mismatch, so users never see a save error
// for a title the UI accepts but the domain cannot save.
const longerTitle = NonEmptyTrimmedString1000.orThrow("Buy milk");
// @ts-expect-error MaxLength1000 does not guarantee MaxLength100.
Todo.from({ title: longerTitle });

// Imagine a UI input component that returns TrimmedString.
// from.parent.parent connects it to the domain field and validates the
// remaining constraints.
const titleFromTrimmingInput: TrimmedString = trim("  Buy milk  ");
const validatedTitle = Todo.props.title.from.parent.parent(
  titleFromTrimmingInput,
);

// No "not a string" or "not trimmed" errors: the input guarantees both.
assertType<
  Result<NonEmptyTrimmedString100, MaxLengthError<100> | MinLengthError<1>>,
  typeof validatedTitle
>();
assertOk(validatedTitle, "Buy milk");

Evolu includes dozens of predefined Types and Type factories. Use Types such as Age, PositiveInt, DateIso, NonEmptyTrimmedString100, Base64Url, and Json directly. Build domain Types with factories such as brand, typed, minLength, maxLength, array, object, union, templateLiteral, transform, discriminatedUnion, and json.

Guarantees

Evolu Type validates values; it does not defend against adversarial JavaScript such as malicious Proxies, mutation during validation, throwing traps, forged built-ins, or code deliberately bypassing TypeScript with any or casts.

Evolu Type trusts application code and audited dependencies. Untrusted code can cause harm far beyond validation and must not run in the application. Defending against it would add complexity without creating a meaningful security boundary.

Runtime assertions still detect accidental developer errors that TypeScript cannot express. They are correctness checks, not defenses against malicious code.

Evolu does not support subclassing native JavaScript objects. Such subclasses can be classified as their reported built-in representation, but their behavior is unspecified.

FAQ

What does a Type represent?

A Type is a lawful, pure codec for an exact semantic domain:

Input           ── partial decode ──▶ Output
CanonicalInput  ◀─── total encode ─── Output

CanonicalInput ⊆ Input

Read each line in the direction of its arrowhead. Input is the complete typed decoding boundary, including candidates that validation can reject and noncanonical representations that decoding can normalize. Output is the validated semantic value. CanonicalInput is the statically known subtype of Input returned by the complete to operation. It can be wider than the values actually emitted when a refinement follows an arbitrary transformation because TypeScript cannot determine which values its encoder returns for the narrowed Output. fromUnknown and the from operations decode; to encodes.

A lawful Type round-trips every Output:

fromUnknown(to(output)) ≈ ok(output)

Encoding can canonicalize a valid Input:

"0042" ──decode──▶ 42 ──encode──▶ "42"

Once canonicalized, repeating the decode-encode cycle must preserve that representation:

"42" ──decode──▶ 42 ──encode──▶ "42"

Here decode means running the complete decoding pipeline, as fromUnknown does, and means equality appropriate for the semantic domain. Validation refinements, Array Types, and Object Types preserve these laws when their contained Types do. A union additionally requires compatible dispatch: it encodes through the first member matching the Output and decodes through the first member accepting the Input. Member ordering is lawful only when those choices agree semantically. Encoded representations can overlap even when member Output types are disjoint.

When encoding returns a refined value unchanged, the refinement can narrow CanonicalInput without changing its JavaScript representation. For example, FiniteNumber has number as its Input, while its Output and CanonicalInput are FiniteNumber: decoding can reject non-finite number candidates, and encoding only receives validated finite Outputs. A transformation can change the representation entirely. For Int64FromInt64String, Input is string, Output is Int64, and CanonicalInput is Int64String. Structural Type factories derive their CanonicalInput recursively from their contained Types.

Why is to total?

Suppose a Type accepts only strings containing decimal digits and decodes them to JavaScript numbers. Parsing "42" is possible, but the Type cannot lawfully declare its Output as number:

digits-only string ──partial decode──▶ number
digits-only string ◀─── total encode ── number  // impossible

number also contains negative and fractional numbers, NaN, positive and negative infinity, and -0. None of those values has a digits-only representation, so to could not encode every valid Output.

One lawful design narrows the Output to the exact representable domain:

digits-only string ──partial decode──▶ NonNegativeSafeInteger
digits-only string ◀─── total encode ── NonNegativeSafeInteger

"0042" ──decode──▶ 42 ──encode──▶ "42"

Another lawful design keeps number as the Output but expands the Input representation to include a canonical string for every number, including "NaN", "Infinity", "-Infinity", and "-0", as well as negative and fractional numbers.

The same principle applies when converting between two representations. Give each representation its own Type with the same exact Output. For example, a string representation and a number representation can both decode to the shared SafeInteger domain:

string ──partial decode──▶ SafeInteger
string ◀─── total encode ── SafeInteger

number ──partial decode──▶ SafeInteger
number ◀─── total encode ── SafeInteger

Conversion decodes the source representation, then total-encodes the shared Output into the target representation. If no lossless shared domain exists, the operation is a partial conversion, migration, or policy decision and should be an explicit function returning Result, not a Type transformation.

Why can a typed operation throw?

TypeScript proves structural assignability, but it cannot describe every runtime invariant. For example, it cannot express whether an object property is own, enumerable, or a data property. It also permits a wider object with excess properties where a narrower object type is expected.

fromUnknown treats such invalid external values as input data and returns a typed error. Typed boundaries instead assert the domain promised by their parameter type. If application code claims an accessor-backed object or an object with excess properties is an Object Output, the assertion throws because the application contract is broken. orThrow and orNull preserve the assertion at their typed Input boundary, then apply getOrThrow or getOrNull only to validation failures returned by the remaining pipeline.

Consequently, structural representation errors such as sparse Arrays, accessors, and excess properties normally do not enter user-facing validation in typed application flows. They violate the producer's declared contract and throw as developer errors. At a genuinely unknown boundary, such as a schema-authoring tool, import, or external protocol, the same issues are legitimate typed validation errors and their formatter messages are useful.

This distinction applies to data failures. Any Type operation, including fromUnknown, can throw when trusted Type-declaration code, such as a successful transformation callback, violates its declared contract.

Materialize accessor values into plain data, remove properties the Type does not represent, or use a different Type. Silently discarding excess data would make the code constructing it dead while appearing to encode it successfully. One exact Object policy also keeps Output membership independent of parsing configuration. Exact structural policies also keep Output membership independent of whether a transformation happens to allocate a new value. Evolu Type therefore does not invoke accessors, discard excess properties, or make to fallible. This keeps to total for every legitimate Output and lets transformations compose without an encoding-error channel.

How should values from another realm be handled?

Values returned by legacy code or another realm can still be uncertain and should be validated. Realm-neutral Types accept an otherwise legitimate representation without requiring conversion merely because its JavaScript built-ins belong to another realm.

When an application trusts both the producer and its return contract, expose that contract as an accurate TypeScript type and use the typed value directly. If the boundary returns unknown, validate it instead of bypassing the boundary with a cast. Use a specialized Type or explicit transformation when the producer uses a different representation that needs adaptation or normalization.

Why doesn't Evolu Type extract data from rich objects?

Some validation libraries parse an object's data projection. An imaginary validation library can enumerate own enumerable string properties and decode them into a fresh plain object. That lets a class instance decode as plain data while its prototype and methods are ignored. The same general policy can treat a Date or Map as an empty Record and can invoke enumerable getters. This is a coherent but intentionally forgiving normalization model.

Evolu Type validates exactly the runtime representation defined by each Type; it does not implicitly project one representation into another. The predefined Object defines an open plain-object representation with unknown values, object defines a closed plain-object representation, and record defines a plain-dictionary representation whose complete set of own properties are its entries. Their realm-neutral plain-object rule uses isPlainObject: it accepts a null prototype or an immediate root prototype with own hasOwnProperty and isPrototypeOf properties. A custom root prototype with the same shape can therefore be classified as plain; other custom prototypes and class instances are rejected. This heuristic assumes trusted JavaScript and is not a security boundary. Every property must be an enumerable data property; inherited members are not entries, while accessors and hidden properties are invalid instead of being invoked or ignored. array similarly defines a dense sequence whose only own properties are length and its indexed data properties; tuple applies the same representation rules with a fixed length and a distinct Type for each position. Only an explicit transform changes the representation. Consequently, is tests exact Output membership and to stays total for valid Outputs.

Why is JsonValue stricter than JSON.stringify?

JSON.stringify is a forgiving data projection. It can invoke toJSON and accessors, discard object properties, replace unsupported array elements and non-finite numbers with null, and normalize -0 to 0. Those rules are useful for ordinary serialization, but they do not preserve an exact value.

JsonValue instead defines data that is already represented as data. Invalid runtime behavior and values are rejected rather than interpreted or silently discarded. Its encoder is total and stack-safe for every valid Output, and JsonValueFromJson preserves the semantic value when it is encoded and decoded, including JavaScript's distinction between -0 and 0. Use an explicit transformation before this boundary when a projection or other normalization is desired.

Why are Types pure and synchronous?

A Type describes data meaning, not work. Time, I/O, dependencies, external state, authorization, and other contextual decisions belong in a Task. Use a Type to decode the data required by that work, then pass the decoded value to a Task. A pure synchronous conversion that can fail can be an ordinary function returning Result.

Keeping those responsibilities separate prevents Evolu Type from becoming a hidden application workflow. It also keeps validation deterministic, dependency-free, immediately composable, and straightforward to test.

What if only decoding is needed?

Use fromUnknown for unknown data. For typed application data, call from at the boundary its input type proves, or use orThrow or orNull for a flat conversion from Input. The canonical to encoder still keeps the Type lawful and composable with transformations and structural Types. A genuinely irreversible operation is a separate function or Task, not a Type transformation.

Core

NameDescription
AnyTypeAny concrete Type, regardless of its particular type parameters.
EvoluTypeErrorError returned when EvoluType rejects a value.
TypeA runtime representation of a TypeScript type, including its encoded input, semantic output, structured errors, and canonical encoding.
TypeErrorA plain structured error produced by a Type operation.
TypeNodeThe common structural shape of every Type, with its specific type parameters erased.
TypeValueErrorA structured error that directly describes a rejected value.
ValidationOptionsConfigures how container Type operations report errors.
InferErrorsThe union of errors a Type can return from fromUnknown.
InferTypeExtracts the Output of a Type.
TypeErrorFormatterFormats a structured TypeError as a human-readable message.
TypeNameA capitalized name identifying a Type node.
EvoluTypeA Type validating Evolu Type declarations.
assertTypeAsserts exact compile-time type equality or that a value belongs to a Type Output domain.

Construction

NameDescription
BrandTypeThe Type returned by brand.
TransformOutputErrorWraps an error produced by the output Type of transform.
TransformTypeThe Type returned by transform.
BrandFactoryReusable factory for creating a Type with a Brand.
TransformErrorAn error produced by transform while decoding or validating its output.
ValidateBrandFactoryNumberNumeric parameter preserving literal types in a BrandFactory.
brandBranded Type.
createTypeCustom Type.
transformTransform Type.

Base

NameDescription
DataErrorAn error containing one or more issues found while validating a candidate as Data.
DataTypeThe root Type for Evolu Data.
InstanceOfErrorError returned when a value is not an instance of the expected constructor.
InstanceOfTypeThe Type returned by instanceOf.
NeverErrorError returned by Never for every value.
ObjectTagNominal evidence that a value has one object tag.
ObjectTagErrorAn error returned when an object does not report the expected tag.
ObjectTagTypeThe Type returned by objectTag.
TypeOfErrorError returned when typeof does not match the expected JavaScript type.
DataEvolu's recursive platform-independent structured-cloneable data domain.
DataIssueOne issue found while validating a candidate as Data.
InstanceConstructorA JavaScript class constructor accepted by instanceOf.
IsDataReturns whether a TypeScript type consists only of Data.
ArrayBufferA realm-neutral JavaScript ArrayBuffer Type for trusted values.
BigIntA JavaScript bigint Type.
BooleanA JavaScript boolean Type.
DataRoot Type for Data values.
DateA realm-neutral JavaScript Date Type for trusted values.
FunctionA JavaScript function Type.
NeverA Type rejecting every value.
ObjectA Type for readonly plain objects with unknown property values.
SymbolA JavaScript symbol Type.
Uint8ArrayA realm-neutral JavaScript Uint8Array Type for trusted values.
UnknownAn infallible Type accepting every value.
instanceOfInstance Type for one constructor.
objectTagRealm-neutral Type trusting an object's reported tag.

String

NameDescription
Base64UrlErrorError returned when a string is not valid Base64Url text.
CapitalizedErrorError returned when capitalized rejects a string.
DateIsoErrorError returned when a string is not a canonical DateIso.
DateIsoFromDateErrorError returned when a Date cannot be represented as DateIso.
IdErrorError returned when a string is not a valid Id.
MnemonicErrorError returned when a string is not a valid English BIP39 Mnemonic.
NameErrorError returned when a string is not a valid Name.
RegexErrorError returned when a string does not match the regular expression supplied to regex.
TableIdThe Type returned by id for one table.
TableIdErrorError returned when a string is not a valid Id for the expected table.
TrimmedErrorError returned when trimmed rejects a string.
Base64UrlBase64Url text without padding.
CapitalizedStringCapitalized String.
DateIsoCanonical ISO date-time String.
DigitDecimal digit from "0" to "9".
Digit1To23Decimal string from "1" to "23".
Digit1To51Decimal string from "1" to "51".
Digit1To59Decimal string from "1" to "59".
Digit1To6Decimal string from "1" to "6".
Digit1To9Decimal digit from "1" to "9".
Digit1To99Decimal string from "1" to "99".
IdEvolu Id: 16 bytes encoded as a 22-character Base64Url.
IdBytesBinary representation of an Id.
MnemonicA valid English BIP39 mnemonic.
NameA non-empty URL-safe name containing at most 64 UTF-16 code units.
NonEmptyTrimmedStringA non-empty TrimmedString.
NonEmptyTrimmedString100A NonEmptyTrimmedString with at most 100 UTF-16 code units.
NonEmptyTrimmedString1000A NonEmptyTrimmedString with at most 1,000 UTF-16 code units.
SimplePasswordA trimmed password containing between 8 and 64 UTF-16 code units.
TrimmedStringA String without surrounding whitespace.
UrlSafeStringNon-empty URL-safe String.
Base64UrlBase64Url text without padding.
capitalizedCapitalized Brand.
CapitalizedStringCapitalized String.
DateIsoCanonical ISO date-time String.
DateIsoFromDateSafely transforms a Date into a canonical DateIso.
DigitDecimal digit from "0" to "9".
Digit1To23Decimal string from "1" to "23".
Digit1To51Decimal string from "1" to "51".
Digit1To59Decimal string from "1" to "59".
Digit1To6Decimal string from "1" to "6".
Digit1To9Decimal digit from "1" to "9".
Digit1To99Decimal string from "1" to "99".
IdEvolu Id: 16 bytes encoded as a 22-character Base64Url.
IdBytesBinary representation of an Id.
idBytesTypeValueLengthByte length of an IdBytes value.
MnemonicA valid English BIP39 mnemonic.
NameA non-empty URL-safe name containing at most 64 UTF-16 code units.
NonEmptyTrimmedStringA non-empty TrimmedString.
NonEmptyTrimmedString100A NonEmptyTrimmedString with at most 100 UTF-16 code units.
NonEmptyTrimmedString1000A NonEmptyTrimmedString with at most 1,000 UTF-16 code units.
SimplePasswordA trimmed password containing between 8 and 64 UTF-16 code units.
StringA JavaScript string Type without additional constraints.
testNameStable valid Name for tests and internal fixtures.
trimmedString Brand without surrounding whitespace.
TrimmedStringA String without surrounding whitespace.
UrlSafeStringNon-empty URL-safe String.
base64UrlToUint8ArrayConverts Base64Url to bytes.
createIdCreates a cryptographically random Id.
createIdAsUuidv7Creates an Id whose bytes use the UUID v7 timestamp layout.
createIdFromStringDeterministically creates an Id from the first 16 SHA-256 bytes.
idTable-specific Id Type.
idBytesToIdConverts IdBytes to an Id.
idToIdBytesConverts an Id to IdBytes.
lengthExact-length Brand for values whose length equals exact.
maxLengthMaximum-length Brand for values whose length is at most max.
minLengthMinimum-length Brand for values whose length is at least min.
regexString Brand constrained by a regular expression.
trimTrims a string and returns a TrimmedString.
uint8ArrayToBase64UrlConverts bytes to Base64Url.

Number

NameDescription
BetweenErrorError returned when between rejects a number.
DecimalStringErrorError returned when a string is not a canonical DecimalString.
FiniteErrorError returned when finite rejects a non-finite number.
GreaterThanErrorError returned when greaterThan rejects a number.
GreaterThanOrEqualToErrorError returned when greaterThanOrEqualTo rejects a number.
Int64ErrorError returned when a bigint is outside the signed 64-bit Int64 range.
Int64StringErrorError returned when a string is not a canonical Int64String.
IntErrorError returned when int rejects a number that is not a safe integer.
LessThanErrorError returned when lessThan rejects a number.
LessThanOrEqualToErrorError returned when lessThanOrEqualTo rejects a number.
MultipleOfErrorError returned when multipleOf rejects a number.
NegativeDecimalStringErrorError returned when negativeDecimalString rejects a decimal string.
NegativeErrorError returned when negative rejects a number.
NonNaNErrorError returned when nonNaN rejects NaN.
NonNegativeDecimalStringErrorError returned when nonNegativeDecimalString rejects a decimal string.
NonNegativeErrorError returned when nonNegative rejects a number.
NonPositiveDecimalStringErrorError returned when nonPositiveDecimalString rejects a decimal string.
NonPositiveErrorError returned when nonPositive rejects a number.
PositiveDecimalStringErrorError returned when positiveDecimalString rejects a decimal string.
PositiveErrorError returned when positive rejects a number.
UInt64ErrorError returned when a bigint is outside the unsigned 64-bit UInt64 range.
AgeA person's age as a NonNegativeInt less than 200.
DecimalStringCanonical string representation of a signed base-10 decimal value.
FiniteNumberFinite Number.
IntSafe integer FiniteNumber.
Int64Signed 64-bit BigInt.
Int64StringDecimal string representation of a signed Int64.
NegativeDecimalStringNegative DecimalString.
NegativeIntNegative Int.
NegativeNumberNegative Number.
NonNaNNumberNumber other than NaN; infinities are allowed.
NonNegativeDecimalStringNon-negative DecimalString.
NonNegativeFiniteNumberNon-negative FiniteNumber.
NonNegativeIntNon-negative Int.
NonNegativeNumberNon-negative Number.
NonPositiveDecimalStringNon-positive DecimalString.
NonPositiveIntNon-positive Int.
NonPositiveNumberNon-positive Number.
PositiveDecimalStringPositive DecimalString.
PositiveFiniteNumberPositive FiniteNumber.
PositiveIntPositive Int.
PositiveNumberPositive Number.
RatioFinite Number from zero to one, inclusive.
UInt64Unsigned 64-bit BigInt.
AgeA person's age as a NonNegativeInt less than 200.
DecimalStringCanonical string representation of a signed base-10 decimal value.
finiteNumber Brand requiring a finite value.
FiniteNumberFinite Number.
intSafe integer Brand.
IntSafe integer FiniteNumber.
Int64Signed 64-bit BigInt.
Int64FromInt64StringTransforms an Int64String into an Int64.
Int64StringDecimal string representation of a signed Int64.
maxPositiveIntMaximum PositiveInt value.
negativeNumber Brand requiring a value less than zero.
negativeDecimalStringDecimalString Brand requiring a value less than zero.
NegativeDecimalStringNegative DecimalString.
NegativeIntNegative Int.
NegativeNumberNegative Number.
nonNaNNumber Brand requiring a value other than NaN.
NonNaNNumberNumber other than NaN; infinities are allowed.
nonNegativeNumber Brand requiring a value greater than or equal to zero.
nonNegativeDecimalStringDecimalString Brand requiring a value greater than or equal to zero.
NonNegativeDecimalStringNon-negative DecimalString.
NonNegativeFiniteNumberNon-negative FiniteNumber.
NonNegativeIntNon-negative Int.
NonNegativeNumberNon-negative Number.
nonPositiveNumber Brand requiring a value less than or equal to zero.
nonPositiveDecimalStringDecimalString Brand requiring a value less than or equal to zero.
NonPositiveDecimalStringNon-positive DecimalString.
NonPositiveIntNon-positive Int.
NonPositiveNumberNon-positive Number.
NumberA JavaScript number, including NaN, Infinity, and -Infinity.
onePositiveIntMinimum PositiveInt value.
positiveNumber Brand requiring a value greater than zero.
positiveDecimalStringDecimalString Brand requiring a value greater than zero.
PositiveDecimalStringPositive DecimalString.
PositiveFiniteNumberPositive FiniteNumber.
PositiveIntPositive Int.
PositiveNumberPositive Number.
RatioFinite Number from zero to one, inclusive.
UInt64Unsigned 64-bit BigInt.
zeroNonNegativeIntMinimum NonNegativeInt value.
betweenNumber Brand requiring a value within an inclusive range.
greaterThanNumber Brand requiring a value greater than min.
greaterThanOrEqualToNumber Brand requiring a value greater than or equal to min.
lessThanNumber Brand requiring a value less than max.
lessThanOrEqualToNumber Brand requiring a value less than or equal to max.
multipleOfNumber Brand requiring an exact decimal multiple of divisor.

Collection

NameDescription
ArrayAccessorIssueAn array element defined by an accessor instead of a data property.
ArrayExcessPropertyIssueAn own array property other than length or an indexed element.
ArrayHoleIssueA missing array element.
ArrayNotArrayErrorError returned when an array input is not an array.
ArrayTypeThe homogeneous readonly-array Type returned by array.
LengthErrorError returned when length rejects a value.
MapExcessPropertyIssueAn own property found on a Map value.
MapKeyCollisionIssueTwo map keys that decode to the same output key.
MapNotMapErrorError returned when a map input is not a Map.
MapTypeThe readonly-map Type returned by map.
MaxLengthErrorError returned when maxLength rejects a value.
MinLengthErrorError returned when minLength rejects a value.
SetExcessPropertyIssueAn own property found on a Set value.
SetNotSetErrorError returned when a set input is not a Set.
SetTypeThe homogeneous readonly-set Type returned by set.
TupleAccessorIssueAn accessor element in a tuple.
TupleExcessPropertyIssueAn undeclared own property in a tuple.
TupleHoleIssueA missing indexed element in a tuple.
TupleInvalidLengthErrorAn error returned when a tuple input has the wrong length.
TupleNotArrayErrorAn error returned when a tuple input is not an Array.
TupleTypeThe fixed-length heterogeneous Type returned by tuple.
ArrayElementIssueAn invalid array element and its index.
ArrayElementsErrorAn array error containing element errors from a typed boundary.
ArrayErrorError returned by array for a non-array value or invalid array items.
ArrayIssueOne structural or element issue found by array.
ArrayItemsErrorAn array error containing structural or element issues.
MapEntriesErrorEntry errors returned by a map operation.
MapErrorError returned while validating a map and its entries.
MapIssueAn invalid key, value, or structure in a map.
MapKeyIssueAn invalid key and its entry index in a map.
MapValueIssueAn invalid value and its entry index in a map.
SetElementIssueAn invalid Set element and its iteration index.
SetElementsErrorA set error containing element errors from a typed boundary.
SetErrorError returned by set for a non-Set value or invalid Set items.
SetItemsErrorA set error containing structural or element issues.
TupleElementIssueAn error returned by one element Type in a tuple.
TupleElementsErrorElement errors possible after a typed tuple boundary was asserted.
TupleErrorAn error returned while validating a tuple.
TupleIssueOne structural or element issue found in a tuple.
TupleItemsErrorAn error containing structural or element issues found in a tuple.
arrayArray Type.
lengthExact-length Brand for values whose length equals exact.
mapMap Type whose keys and values must match their respective Types.
maxLengthMaximum-length Brand for values whose length is at most max.
minLengthMinimum-length Brand for values whose length is at least min.
setSet Type whose every element must match one Type.
tupleTuple Type.

Objects

NameDescription
ObjectErrorAn error returned while validating an object and its properties.
ObjectExcessPropertyErrorAn error returned for an input property outside an Object Type's allowed key domain.
ObjectMissingPropertyErrorAn error returned when a required object property is absent.
ObjectNotObjectErrorAn error returned when an object input is not an object.
ObjectPropertiesErrorAn error returned while validating the properties of an object.
ObjectPropertyAccessErrorAn error returned when a present object property is not represented as an enumerable data property.
ObjectUnexpectedPrototypeErrorAn error returned when an object input falls outside its supported plain-object prototype boundary.
OptionalPropertyAn optional property used to construct an object Type.
RecordAccessorIssueAn accessor property rejected by record.
RecordCollisionIssueTwo record keys that decode to the same output key.
RecordNonEnumerableIssueA non-enumerable property rejected by record.
RecordNotPlainRecordErrorError returned when a record input is not a plain object.
RecordNotRecordErrorError returned when a record input is not an object.
RecordTypeThe Type returned by record.
NullableToOptionalPropsMaps object properties whose Union Type includes Null to optional properties.
ObjectPropsProperties used to construct an object Type.
ObjectTypeThe Type returned by object.
PartialObjectPropsMaps every required object property Type to an optional property.
RecordEntriesErrorEntry errors returned by a record operation.
RecordErrorError returned while validating a record and its entries.
RecordIssueAn invalid key, value, or property structure in a record.
RecordKeyIssueAn invalid key and its source property key in a record.
RecordStructuralIssueA property-structure issue returned by record.
RecordValueIssueAn invalid value and its property key in a record.
nullableToOptionalObject Type making every property whose Union Type includes Null optional.
objectPlain object Type.
omitObject Type without the selected declared properties.
optionalOptional object property.
partialObject Type with every property optional.
recordRecord Type.

Unions

NameDescription
LiteralErrorError returned when a value does not equal the expected literal.
LiteralTypeThe Type returned by literal.
UnionMemberErrorAn error returned by one union member and its index.
UnionTypeThe Type returned by union.
UnionErrorError returned when every member of a union rejects an input.
UnionInputTypeA root Type validating the encoded Inputs accepted by union.
NullLiteral Type accepting only null.
UndefinedLiteral Type accepting only undefined.
literalLiteral Type.
nullishOrUnion Type containing the supplied Type, null, and undefined.
nullOrUnion Type containing the supplied Type and null.
undefinedOrUnion Type containing the supplied Type and undefined.
unionUnion Type.

Template literals

NameDescription
TemplateLiteralErrorError returned when a string does not match a template literal declaration.
TemplateLiteralParserTypeThe parsing Type returned by templateLiteralParser.
TemplateLiteralTypeThe validating string Type returned by templateLiteral.
templateLiteralTemplate literal Type for validation.
templateLiteralParserTemplate literal Type that parses canonical strings into Tuples.

Discriminated unions

NameDescription
DiscriminatedUnionDiscriminatorErrorAn error returned when no member of discriminatedUnion matches.
DiscriminatedUnionMemberIssueA selected-member issue returned by discriminatedUnion.
DiscriminatedUnionObjectErrorAn error returned when a value cannot be routed through Object.
DiscriminatedUnionPropertyAccessErrorAn error returned when the discriminator for discriminatedUnion is not an own enumerable data property.
DiscriminatedUnionTypeThe routed Type returned by discriminatedUnion.
TypedA TypeScript interface with a literal type property.
DiscriminatedUnionErrorAn error returned while selecting a member in discriminatedUnion.
DiscriminatedUnionInputTypeA root Type validating Inputs accepted by discriminatedUnion.
DiscriminatedUnionMemberErrorAn error returned by the member selected by discriminatedUnion.
ExtractTypedExtracts members of a Typed Output union by their type literal.
TypedTypeThe ObjectType returned by typed.
discriminatedUnionDiscriminated union Type.
typedCreates an ObjectType with a literal type property.

Results

NameDescription
UnknownNextResultA nextResult Type with unknown value, error, and done components.
UnknownResultA result Type for Result<unknown, unknown>.
UnknownNextResultA nextResult Type with unknown value, error, and done components.
UnknownResultA result Type for Result<unknown, unknown>.
nextResultCreates a Type for producer Results with value, error, or done outcomes.
resultCreates a Type for Result values.

Recursive

NameDescription
LazyTypeA deferred Type with an explicit recursive type declaration.
lazyCreates a lazy Type for recursive definitions.

JSON

NameDescription
JsonErrorAn error returned when a string does not contain valid JSON text.
JsonObjectAn exact JSON object containing only JsonValue properties.
JsonObjectInputA candidate JSON object before exact runtime validation.
JsonObjectTypeThe exact top-level JSON object Type.
JsonValueErrorAn error containing one or more issues found while validating a candidate as an exact JsonValue.
JsonValueTypeThe exact root Type of in-memory JSON data values.
JsonA String Brand proving that its exact text parses to JsonValue.
JsonArrayAn exact JSON array containing only JsonValue elements.
JsonArrayInputA candidate JSON array before exact runtime validation.
JsonValueAn exact in-memory JSON data value.
JsonValueInputA candidate JSON value before exact runtime validation.
JsonValueIssueOne issue found while validating a candidate as an exact JsonValue.
JsonA String Brand proving that its exact text parses to JsonValue.
JsonArrayExact top-level JSON array Type.
JsonObjectExact top-level JSON object Type.
JsonValueExact root Type for JsonValue data trees.
JsonValueFromJsonTransformation Type that parses Json into JsonValue.
jsonBranded Json Type and conversions for another Type.
jsonToJsonValueConverts proven Json text to an exact JsonValue.
jsonValueToJsonConverts an exact JsonValue to canonical Json text.

Localization

VariableDescription
localizeTypesCreates localized copies of selected Type declarations.