API reference / @evolu/common / Type

Type

🧩 Validation, Parsing, and Transformation

Intro

You probably know Zod. Evolu has Type.

Evolu Type exists because no existing validation/parsing/transformation library fully met our needs:

  • Result-based error handling: Leveraging Result instead of throwing exceptions.
  • Consistent constraints: Enforcing Brand for all constraints.
  • Typed errors with decoupled formatters: Avoiding coupling error messages with validators.
  • No user-land chaining: Designed with ES pipe operator in mind.
  • Selective validation/transformation: Skipping parent Type validations and transformations when TypeScript's type system can be relied upon.
  • Bidirectional transformations: Supporting transformations in both directions.
  • Minimal and transparent code: No runtime dependencies or hidden magic.

Note: A proper quickstart guide is on the way. In the meantime, each type includes its own usage example, and you can (and should) check the tests for practical demonstrations of the API. Or dang, just read the code. It's simple.

  • Evolu Type is:

  • A TypeScript type with a Brand whenever it's possible.

  • A function to create a value of that type, which may fail.

  • A function to transform value back to its original representation, which cannot fail.

Types are chainable. The chain starts with a Base Type that refines an unknown value into something and can continue with further refinements or transformations. For example, NonEmptyTrimmedString100 chain looks like this:

Unknown -> String -> TrimmedString -> NonEmptyTrimmedString100

For NonEmptyTrimmedString100, the parent Type is TrimmedString. For TrimmedString, the parent Type is String.

The parent of the String Type is the String Type itself. All Base Types fromParent functions are just a typed alias to fromUnknown to ensure that fromParent and toParent can be called on any Type.

Speaking of fromParent and toParent, those functions exist to bypass parent Types when we can rely on TypeScript types.

Type transformations should be reversible. If you need an irreversible transformation, such as TrimString (trimming is not reversible as untrim can't know what has been trimmed), you can do that, but note in JSDoc that to will not restore the original representation. You can also use assert: assert(false, "Untrim is not possible").

Tip

If necessary, write globalThis.String instead of String to avoid naming clashes with Base Types.

Design Decision:

While the from function can fail, the to function cannot. This simplifies the model by ensuring that every valid input has a corresponding valid output, eliminating the risk of edge cases caused by irreversible operations.

Base Factories

FunctionDescription
arrayArray of a specific Type.
baseBase Type.
brandBranded Type.
instanceOfinstanceof Type.
literalLiteral Type.
nullishOrunion(undefined, null, T) Type.
nullOrunion(null, T) Type.
objectObject Type.
recordRecord of a key Type and value Type.
recursiveRecursive Type.
transformType that transforms values between FromType and ToType.
tupleTuple Type.
undefinedOrunion(undefined, T) Type.
unionUnion Type.

Base Types

VariableDescription
BigInt-
Boolean-
DateJavaScript Date.
Function-
JsonValueJSON-compatible value: string, FiniteNumber, boolean, null, JsonArray, or JsonObject.
Null-
Number-
String-
Uint8Array-
Undefined-
Unknown-

String

NameDescription
Base64UrlURL-safe Base64 string.
CurrencyCodeA three-letter ISO 4217 currency code (e.g., USD, EUR).
DateIsoTransforms a Date into a DateIsoString string and vice versa.
DateIsoStringISO 8601 date-time string.
IdId Type.
JsonJSON-string Type.
JsonValueFromStringTransform Type that parses a JSON into a JsonValue and serializes a JsonValue back into a JSON string.
lengthExact length.
maxLengthMaximum length.
minLengthMinimum length.
MnemonicThe mnemonic, also known as a "seed phrase," is a set of 12 words in a specific order chosen from a predefined list (BIP39). It provides a human-readable way to store a private key securely. The mnemonic is generated safely on the user's device using cryptographically secure random number generation, ensuring it remains private and unique.
NanoIdDefault NanoId.
NonEmptyString-
NonEmptyString100-
NonEmptyString1000-
NonEmptyTrimmedString-
NonEmptyTrimmedString100-
NonEmptyTrimmedString1000-
regexString matching a regular expression.
SimpleNameSimple alphanumeric string for naming.
SimplePasswordTrimmed string between 8 and 64 characters, branded as SimplePassword.
String-
String100-
String1000-
trimTrims leading and trailing whitespace from a string.
trimmedTrimmed string.
TrimmedStringTrimmed string
TrimmedString100-
TrimmedString1000-
TrimStringTrims leading and trailing whitespace from a string.
idType Factory to create branded Id Type for a specific table.

Number

VariableDescription
betweenNumber within a range, inclusive.
Between1And10-
finiteFinite number.
FiniteNumberFinite number.
greaterThanNumber greater than a specified value.
greaterThanOrEqualToNumber ≥ a specified value.
intInteger within the safe range of JavaScript numbers.
IntInteger within the safe range of JavaScript numbers.
Int6464-bit signed integer.
Int64StringStringified Int64.
lessThanNumber less than a specified value.
lessThanOrEqualToNumber ≤ a specified value.
multipleOfNumber that is a multiple of a divisor.
negativeNegative number.
NegativeInt-
NegativeNumber-
nonNaNNumber that is not NaN.
NonNaNNumber-
nonNegativeNon-negative number.
NonNegativeInt-
NonNegativeNumber-
nonPositiveNon-positive number.
NonPositiveInt-
NonPositiveNumber-
NumberFromStringTransforms a NonEmptyTrimmedString into a FiniteNumber.
positivePositive number.
PositiveInt-
PositiveNumber-

Array

NameDescription
JsonArrayJSON-compatible array of JsonValue elements.
lengthExact length.
maxLengthMaximum length.
minLengthMinimum length.
arrayArray of a specific Type.

Object

NameDescription
JsonObjectJSON-compatible object with string keys and JsonValue values.
nullableToOptionalConverts each “nullable” property (a union that includes Null) into an optional property. This means consumers can omit the property entirely, or set it to null, or set it to the non-null member of the union.
objectObject Type.
omitCreate a new object Type by omitting some keys.
partialCreates a partial object type where all properties are optional.
recordRecord of a key Type and value Type.

Utilities

NameDescription
BrandFactoryHelper type for Type Factory that creates a branded Type.
MergeObjectTypeErrorsMerge Error and ParentError into one ObjectError so tooltips and error messages are easier to read.
TypeErrorsUnion of all TypeErrors defined in the Type.ts file, including base type errors (e.g., StringError, NumberError), composite type errors (ArrayError, ObjectError), and optionally, user-defined extra errors.
TypeNameUnique identifier for a Type.
createBaseTypeErrorFormatterCreates a formatter function for a base TypeError.
createFormatTypeErrorCreates a unified error formatter that handles both Evolu Type's built-in TypeErrors and custom errors. It also lets us override the default formatting for specific errors.
createTypeErrorFormatterCreates a formatter function for TypeError.
isTypeChecks if the given value is an Type.

Other

NameDescription
ArrayError-
ArrayTypeArrayType extends Type with an additional element property for reflection.
BetweenError-
BigIntError-
BigIntFromStringError-
BooleanError-
BrandType-
BrandWithoutRefineError-
CurrencyCodeError-
DateIsoStringError-
EvoluTypeError-
FiniteError-
FunctionError-
GreaterThanError-
GreaterThanOrEqualToError-
IdError-
IdType-
InstanceOfError-
InstanceOfType-
Int64Error-
Int64StringError-
IntError-
JsonError-
JsonObject-
JsonObjectInput-
JsonValueFromStringError-
LengthError-
LessThanError-
LessThanOrEqualToError-
LiteralError-
LiteralType-
MaxLengthError-
MinLengthError-
MnemonicError-
MultipleOfError-
NegativeError-
NonNaNError-
NonNegativeError-
NonPositiveError-
NullError-
NumberError-
NumberFromStringError-
ObjectError-
ObjectTypeObjectType extends Type with an additional props property for reflection.
ObjectWithRecordError-
ObjectWithRecordTypeObjectWithRecordType extends Type with additional props and record properties for reflection.
OptionalType-
PositiveError-
RecordError-
RecordTypeRecordType extends Type with additional key and value properties for reflection.
RecursiveType-
RegexError-
StringError-
TransformTypeTransformType extends Type with additional fromType and toType properties for reflection.
TrimmedError-
TupleError-
TupleTypeTupleType extends Type with an additional elements property for reflection.
Type-
TypeError-
TypeErrorWithReason-
Uint8ArrayError-
UndefinedError-
UnionError-
UnionTypeUnionType extends Type with an additional members property for reflection.
AnyType-
Base64Url-
Base64UrlError-
Between1And10-
CurrencyCode-
DateIsoString-
FiniteNumber-
Id-
InferError-
InferErrors-
InferInput-
InferName-
InferParent-
InferParentError-
InferType-
Int-
Int64-
Int64String-
IsUnionWithNull-
Json-
JsonArray-
JsonArrayInput-
JsonValue-
JsonValueError-
JsonValueInput-
Mnemonic-
NanoId-
NanoIdError-
NegativeInt-
NegativeNumber-
NonEmptyString-
NonEmptyString100-
NonEmptyString1000-
NonEmptyTrimmedString-
NonEmptyTrimmedString100-
NonEmptyTrimmedString1000-
NonNaNNumber-
NonNegativeInt-
NonNegativeNumber-
NonPositiveInt-
NonPositiveNumber-
NullableToOptionalProps-
NullTypeInMembers-
PositiveInt-
PositiveNumber-
SimpleName-
SimpleNameError-
SimplePassword-
SimplePasswordError-
String100-
String1000-
TransformBrandFactory-
TransformNullable-
TrimmedString-
TrimmedString100-
TrimmedString1000-
TypeErrorFormatter-
BigIntFromString-
EvoluTypeValidates that an unknown value is an Evolu Type (i.e., satisfies AnyType).
formatBetweenError-
formatBigIntError-
formatBigIntFromStringError-
formatBooleanError-
formatCurrencyCodeError-
formatDateIsoStringError-
formatFiniteError-
formatFunctionError-
formatGreaterThanError-
formatGreaterThanOrEqualToError-
formatIdError-
formatInstanceOfError-
formatInt64Error-
formatInt64StringError-
formatIntError-
formatIsTypeError-
formatJsonError-
formatJsonValueFromStringError-
formatLengthError-
formatLessThanError-
formatLessThanOrEqualToError-
formatLiteralError-
formatMaxLengthError-
formatMinLengthError-
formatMnemonicError-
formatMultipleOfError-
formatNegativeError-
formatNonNaNError-
formatNonNegativeError-
formatNonPositiveError-
formatNullError-
formatNumberError-
formatNumberFromStringError-
formatPositiveError-
formatRegexError-
formatStringError-
formatTrimmedError-
formatUint8ArrayError-
formatUndefinedError-
idTypeValueLength-
createIdCreates an Id.
formatArrayError-
formatObjectError-
formatObjectWithRecordError-
formatRecordError-
formatSimplePasswordError-
formatTupleError-
formatUnionError-
isOptionalTypeDetermines if a given type is an OptionalType.
isUnionType-
jsonCreates a transform Type that serializes a given Type into a branded JSON string. The transformation is reversible, ensuring that we can safely parse it back.
optionalOptional Type.

Was this page helpful?