ArkType

Change ArkType's defaults and error messages globally, for a scope or for a single Type.

Levels

Config can be set at three levels. A more specific level overrides a broader one.

Global

Call configure in its own file, and import that file before anything creates a Type:

config.ts
import { configure } from "arktype/config"

configure({ numberAllowsNaN: true })
app.ts
import "./config.ts"
import { type } from "arktype"

// true
type.number.allows(Number.NaN)

warningConfigure before any Type is created

Global config is fixed when the first Type is created, whether by a definition or by referencing a keyword like type.number, and calling configure after that throws unless it changes nothing, as when a test runner resets its modules and the config file runs again. Importing "arktype" first is fine, and configure can be imported from either "arktype" or "arktype/config".

Global config belongs to the app. A package others install shouldn't call configure: it would change the app's own Types, or throw there if the app created one first. Give a package's Types their options in a scope or in each Type.

If your package.json sets "sideEffects": false, a bundler leaves out an import made only for its side effects, so the bundle runs without your config. List the file there instead: "sideEffects": ["./src/config.ts"].

Scope

Pass config as the second argument to scope or type.module. It applies to every Type parsed in that scope:

const 
const $: Scope<{
    User: {
        age: number;
    };
}>
$
= scope(
{ User: { age: "number < 100" } }, { max: { actual: () => "unacceptably large" } } ) // ArkErrors: age must be less than 100 (was unacceptably large)
const $: Scope<{
    User: {
        age: number;
    };
}>
$
.export().User({ age: 101 })
// ArkErrors: age must be at most 100 (was unacceptably large)
const $: Scope<{
    User: {
        age: number;
    };
}>
$
.type({ age: "number <= 100" })({ age: 101 })

Type

.configure adds metadata, like a description or error parts, to a Type. It applies wherever that Type is referenced, but not to the Types inside it:

const const Password: Type<string>Password = type("string >= 8").configure({
	message: "Use 8 or more characters"
})

const 
const User: Type<{
    email: string;
    password: string;
}>
User
= type({
email: "string.email", password: const Password: Type<string>Password }) // ArkErrors: password: Use 8 or more characters User({ email: "david@arktype.io", password: "ez123" })

Options

optiondefaultlevels
onUndeclaredKey"ignore"global, type ("+")
exactOptionalPropertyTypestrueglobal, scope
numberAllowsNaNfalseglobal
numberAllowsInfinityfalseglobal
dateAllowsInvalidfalseglobal
jitlessfalse, or true where new Function is blockedglobal, scope
onFailnull, which returns ArkErrorsglobal, scope
errors"all"global, scope
mutatesInputfalseglobal, scope
keywords{}global
ambientArkType's built-in keywordsscope
localeenglobal
an error code, like divisorArkType's messagesglobal, scope
toJsonSchemadraft 2020-12, throwing for what it can't expressglobal, scope

A Type's own options are its metadata, including the parts of its errors.

Error messages

ArkType's built-in error messages are designed to be good enough to ship as-is, and you have three ways to customize them when needed: templated (description / expected), labeled (label) and custom (message). Choose in this order:

  1. Use the built-in error messages first. ArkType's defaults are specific and readable out of the box (must be non-empty, must be even, must be an email address), and because they follow a must be ___ template, they compose automatically across unions — "string.email | string.uuid" reports must be an email address or a UUID. Give them a try before reaching to customize every field.
  2. Configure description when you want custom wording that still composes. If you're happy with must be ___ messages and plan to reuse a Type in unions or intersections, pass a phrase like .describe("a valid email") instead of a full sentence so ArkType keeps merging it into natural-language union errors (must be a phone number, a username or a valid email) and reuses it in .description and JSON Schema.
  3. Configure a label to name a field in its messages. Most custom messages only exist to say which field failed: Unit price must be greater than 0. .label("Unit price") puts that name in front of every built-in message for the value, so unitPriceCents: type("number > 0").label("Unit price") reads Unit price must be positive, Unit price must be a number or Unit price must be a number (was missing), while the error's path stays unitPriceCents for a form to bind. It's one call where a message would be one per check, though unlike a description it names only the value it's on, not the Types nested inside it.
  4. Chain constraint methods with a message for custom per-check sentences. Most Types aren't composed into unions whose errors need to read as one sentence — for forms and standalone fields, you just want exact sentences for each condition that can fail. ArkType has chained methods for every built-in constraint, and passing a message as the last argument (e.g. type.string.atLeastLength(1, "Name is required").matching(..., "...")) is the easiest way to give each check its own message. Use .message() for a whole Type, a keyword or a union, and .describe() for what it must be, rather than .configure({ message }) or .configure({ description }).
  5. Save .narrow() for rules built-in constraints can't express, like a rule across fields, one that depends on another field's value, or a check from another library. Don't rewrite a length, range, divisor, pattern, non-empty array or keyword like string.email as a .narrow() just to attach a custom error message — chaining the constraint method keeps the check visible to ArkType's set algebra, JSON Schema generation and precompiler.

Put each check on the value it checks, not on the object or array holding it. countries: type.string.array().atLeastLength(1, "Pick a country") reports at countries even while other keys are invalid, where a .narrow() on the object reading countries.length runs only once every key is valid. The same goes for a nested key: limit: Money.merge({ amount_cents: type.number.moreThan(0, "Enter a limit above zero") }).

const 
const User: Type<{
    name: string;
    age: number;
    email: string;
    seats: number;
}>
User
= type({
name: type.string .atLeastLength(1, "Name is required") .matching(/^[a-z\s'-]*$/i, "Enter a valid name"), age: type("number >= 18").describe("an adult's age"), email: type("string.email").message("Enter a valid email"), seats: type("1 <= number.integer <= 10").label("Seats") }) // ArkErrors: name: Name is required // age must be an adult's age // email: Enter a valid email // Seats must be at most 10 User({ name: "", age: 3, email: "x", seats: 12 })

expected, actual and message each take a string or a function. See Errors for what an error contains.

description

What follows "must be" in a message. Because it fits into ArkType's template, it composes cleanly across unions and is reused by the Type's .description, missing required property messages (e.g. email must be a valid email (was missing)) and JSON Schema output — reach for it when you want must be ___ errors that compose:

const const Email: Type<string>Email = type("string.email").describe("a valid email")
const const Username: Type<string>Username = type(/^[a-z0-9_]{3,20}$/).describe("a username")
const const Phone: Type<string>Phone = type(/^\d{10}$/).describe("a phone number")
const const Contact: Type<string>Contact = type.or(const Email: Type<string>Email, const Username: Type<string>Username, const Phone: Type<string>Phone)

// ArkErrors: must be a phone number, a username or a valid email
Contact("!")

label

What a field is called in its messages, written before each one ArkType writes for the value. Use it where the only reason for a custom message would be to name the field:

const 
const LineItem: Type<{
    unitPriceCents: number;
    quantity: number;
}>
LineItem
= type({
unitPriceCents: type("number > 0").label("Unit price"), quantity: type("number.integer > 0").label("Quantity") }) // ArkErrors: Unit price must be positive // Quantity must be a number (was missing) LineItem({ unitPriceCents: 0 })
  • The label is part of each error's message, at unitPriceCents, so a form library, flatMessagesByPath, a toast and summary all say it. The error's path keeps the key, and a summary leaves out only the key the label names, keeping where it is: items[0]: Unit price must be positive.
  • A message, whether passed to a constraint method or set with .message(), is said as written. A label names the checks that have none, so type.number.moreThan(0, "Enter a price").label("Price") reads Enter a price for 0 and Price must be a number for "1".
  • A narrow saying what its value must be is labeled too: type("string").narrow((s, ctx) => isPercent(s) || ctx.mustBe("between 0 and 100")).label("Percent") reads Percent must be between 0 and 100, as does ctx.reject({ expected }). ctx.reject({ message }) is said as written.
  • Like .describe(), .label() applies to the Type it's called on, not to the Types inside it: a label on an object names what isn't an object, and each key keeps its own. A union of branches labeled alike names them together.
  • toJsonSchema writes a label as the schema's title unless it has one.
  • An empty label is no label, so .label("") removes the one a Type has.

expected

Like description, but only for error messages, where it takes precedence. A function receives the error, so it can read code, data and path:

const const Password: Type<string>Password = type("string >= 8").configure({
	expected: ctx =>
		ctx.code === "minLength" ? `${ctx.rule} characters or more` : "a password"
})

// ArkErrors: must be 8 characters or more
Password("ez123")

// ArkErrors: must be a password
Password(12345678)

actual

What a message ends with, as "(was …)". By default only a missing key's does, with "(was missing)": a message leaves out what the value was, though every error's actual still describes its data, like "5" or "an object", for a message function to read. Configure a string, or a function of the data, then the error, to write one:

const const Age: Type<number>Age = type("number <= 100").configure({ actual: data => `${data}` })

// ArkErrors: must be at most 100 (was 101)
Age(101)

message

One whole sentence in place of "must be expected". It's the error's message, so it's what a Standard Schema consumer, like a form library, shows beside a field, and a summary writes it after the error's path and a colon.

Pass it beside a constraint, as the last argument to .atLeastLength(), .lessThan(), .matching() or any other constraint method, and only that constraint says it, as Zod's .min(8, "...") does:

const const Password: Type<string>Password = type.string
	.atLeastLength(8, "Use 8 or more characters")
	.matching(/[0-9]/, "Include a number")
	.matching(/[A-Z]/, "Include a capital letter")

// ArkErrors: Include a number
//            Include a capital letter
//            Use 8 or more characters
Password("short")

// a value of the wrong type keeps arktype's text
// ArkErrors: must be a string
Password(5)

.message(text) configures the whole Type, as .configure({ message: text }) does, so a value of the wrong type and a missing key say it too:

const 
const Signup: Type<{
    email: string;
}>
Signup
= type({
email: type("string.email").message("Enter a valid email") }) const
const out: ArkErrors | {
    email: string;
}
out
= Signup({ email: "x" })
if (
const out: ArkErrors | {
    email: string;
}
out
instanceof type.errors) {
// email: Enter a valid email const out: ArkErrorsout.summary // Enter a valid email const out: ArkErrorsout.issues[0].message } // a missing key says what its value's message does // ArkErrors: email: Enter a valid email Signup({})

A message is never composed into another error's, as an expected is, and it applies to the constraint or the Type it's configured on:

  • A union's error lists what its branches expected, not their messages, unless every failing branch has the same message, which the union's error then says. It lists them too where that message is one configured by code rather than on each branch's Type, or begins as arktype's own would.
  • A message on a union replaces what it lists. To say what a union must be instead, describe it: type({ a: "string" }).or({ b: "number" }).describe("a shape") says must be a shape.
  • A message on a pipe is also the message of the errors validating its output.
  • A missing key says the message of its whole value, so configure that last, after any .pipe() or .to().
  • A message doesn't apply to the Types inside its own, so one on an object is what data that isn't an object says, and each key keeps its own.
  • A message on a Type is what every check of it says. For a check written in a string definition, or a keyword's, like string.email's pattern, pass the check's error code as a selector, as in type("string >= 8").message("Use 8 or more characters", "minLength").

"domain" selects a value of the wrong type, and "self" the Type's own node, whose message a missing key says. Beside constraints' messages, they give every failure its own:

const const Sku: Type<string>Sku = type.string
	.matching(/^[A-Z]{3}-\d{4}$/, "SKU looks like ABC-1234")
	.message("SKU is required", "self")
	.message("SKU must be text", "domain")

const 
const Product: Type<{
    sku: string;
}>
Product
= type({ sku: const Sku: Type<string>Sku })
// ArkErrors: sku: SKU is required Product({}) // ArkErrors: sku: SKU must be text Product({ sku: 5 }) // ArkErrors: sku: SKU looks like ABC-1234 Product({ sku: "x" })

A code selects every check of that kind in the Type, a nested key's included, so configure a key's value rather than the object around it, or pass the message to the constraint method. A message configured without a selector replaces those configured before it, a constraint's included, and a constraint added after it makes a Type whose missing key doesn't say it, so add a whole-value message's "self" and "domain" after the constraints.

A function receives the error, including its expected and actual. A summary writes its text after the path and a colon as it does a string's, but a missing key doesn't say it:

const const Email: Type<string>Email = type("string.email").message(ctx => `Enter ${ctx.expected}`)

// ArkErrors: Enter an email address
Email("x")

// ArkErrors: Enter a string
Email(5)

A summary tells a sentence of yours by its text. A message that begins as arktype's own would, with must be and the error's expected, reads on from its path with no colon, whether it's a string or what a function returns:

const 
const Entry: Type<{
    age: number;
}>
Entry
= type({
age: type("number").message( ctx => `must be ${ctx.expected} (was ${ctx.actual})` ) }) // ArkErrors: age must be a number (was a string) Entry({ age: "5" })

Each function also receives the active locale as its last argument, so it can write its text in the language a message is read in. A locale also decides how a summary places a path before a message.

Form fields

A form library reading a Type through Standard Schema, like TanStack Form or react-hook-form's standardSchemaResolver, shows each issue's message beside its field, or in a toast or summary away from it. Start with the built-in messages, which read well beside a field with nothing to configure, while a summary puts each one after its path:

const 
const Booking: Type<{
    name: string;
    email: string;
    seats: number;
}>
Booking
= type({
name: "string > 0", email: "string.email", seats: "1 <= number.integer <= 10" }) // ArkErrors: name must be non-empty // email must be an email address // seats must be at most 10 Booking({ name: "", email: "x", seats: 12 })

Customize a field only when its copy has to differ. Where a message would exist only to name the field, like Unit price must be greater than 0 for unitPriceCents, write a label instead. A field whose message you wouldn't otherwise write needs neither.

For copy of your own, a field's empty state is usually "" or undefined, so choose a required field's message by which of those it should cover:

const 
const Signup: Type<{
    name: string;
    nickname: string;
}>
Signup
= type({
// a whole-value message: "" and undefined both say it name: type("string > 0").message("Name is required"), // a constraint's message: only a string too short says it nickname: type.string.atLeastLength(1, "Nickname is required") }) // ArkErrors: name: Name is required // nickname must be a string Signup({ name: undefined, nickname: undefined })

Each is one expression, so write it where the field is defined rather than in a helper like requiredString(message), which hides which of the two the field gets.

  • A field that must hold more than whitespace is string.nonblank, which rejects "" and " " and keeps the value as it is: "string.nonblank" reads must be non-blank. string.trim transforms it instead.
  • An optional field a form leaves as "" is a union with '', like "string.email | ''", whose own text is must be an email address or empty. For copy of your own, configure the whole union, as in type("string.email | ''").message("Enter a valid email or leave it blank"). A website is "string.url.http | ''", since string.url accepts mailto: and javascript:.
  • A pattern beside a length reports both for "", as must be non-empty and the pattern's message. Let the pattern match "", with * rather than +, so an empty field says only that it's required: type("0 < string <= 50").matching(/^[a-z ]*$/i, "Use letters only").
  • A rule about a value computed from the data, like an order's total, can check what a pipe computes rather than narrow the input: Order.pipe(totalOf, type({ total: type.number.moreThan(0, "Add something to the order") })).

By code

Globally or in a scope, configure errors by their code. A function's ctx is typed by its code:

const 
const mod: Module<{
    isEven: number;
}>
mod
= type.module(
{ isEven: "number % 2" }, { divisor: { expected: ctx => `% ${ctx.rule} !== 0`, message: ctx => `${ctx.actual} ${ctx.expected}` } } ) // ArkErrors: 3 % 2 !== 0
const mod: Module<{
    isEven: number;
}>
mod
.isEven(3)

A key that "+": "reject" disallows has the code undeclared:

const 
const $: Scope<{
    User: {
        name: string;
    };
}>
$
= scope(
{ User: { "+": "reject", name: "string" } }, { undeclared: { message: "This key isn't allowed" } } ) // ArkErrors: age: This key isn't allowed
const $: Scope<{
    User: {
        name: string;
    };
}>
$
.export().User({ name: "Alice", age: 42 })

Each kind of constraint, like domain or divisor, also takes a description function. It receives the constraint and changes how it is described everywhere, not only in errors.

locale

Error messages are written in English by default. Configure a locale to write them in another language:

config.ts
import { configure } from "arktype/config"
import { de } from "arktype/locales/de"

configure({ locale: de })
app.ts
import "./config.ts"
import { type } from "arktype"

// ArkErrors: muss eine Zeichenkette sein
type.string(5)

locale can also be a function that returns a locale each time a message is read. See i18n.

keywords

Configure built-in keywords like string.email by name. Each takes a description or the same options as .configure:

config.ts
import { configure } from "arktype/config"

configure({
	keywords: {
		string: "text",
		"string.email": {
			actual: () => "definitely fake"
		}
	}
})
app.ts
import "./config.ts"
import { type } from "arktype"

const 
const User: Type<{
    name: string;
    email: string;
}>
User
= type({
name: "string", email: "string.email" }) // ArkErrors: name must be text // email must be an email address (was definitely fake) User({ name: 5, email: "449 Canal St" })

ambient

Scope-only. Overrides the ambient keywords a scope or type.module falls back to when resolving references. Pass {} to opt out of ArkType's built-in keywords entirely, a Module (such as ark.export("string", "number")), or a plain record of Types, Generics and Modules:

import { ark, scope } from "arktype"

const 
const dsl: Scope<{
    Email: string;
    readonly " ambient": {
        string: string.submodule;
    };
}>
dsl
= scope({ Email: "string.email" }, { ambient: ark.export("string") })

See Ambient for shadowing, chaining and clean-slate DSL scopes, or Default scope to restrict the default keywords across a whole program at the type level.

onUndeclaredKey

Like TypeScript, ArkType ignores keys an object doesn't declare by default. There are three behaviors:

  • "ignore" (default): allow undeclared keys and keep them in the output
  • "delete": allow undeclared keys and output only declared ones
  • "reject": fail on undeclared string keys

An undeclared symbol key passes "reject" and isn't in "delete"'s output.

Set it for one object with "+", or change the default globally:

config.ts
import { configure } from "arktype/config"

configure({ onUndeclaredKey: "delete" })
app.ts
import "./config.ts"
import { type } from "arktype"

const 
const UserForm: Type<{
    name: string;
}>
UserForm
= type({
name: "string" }) // { name: "Alice" } UserForm({ name: "Alice", age: "42" })

exactOptionalPropertyTypes

By default, ArkType treats optional keys as TypeScript does with exactOptionalPropertyTypes: an optional key can be omitted, but not set to undefined.

const 
const MyObj: Type<{
    key?: number;
}>
MyObj
= type({
"key?": "number" }) // {} MyObj({}) // ArkErrors: key must be a number MyObj({ key: undefined })

Add | undefined to keys that should accept it. If your tsconfig doesn't enable exactOptionalPropertyTypes, you can set ArkType's to false to match, which is also how Zod and most other validators treat optional keys and defaults:

config.ts
import { configure } from "arktype/config"

configure({ exactOptionalPropertyTypes: false })
app.ts
import "./config.ts"
import { type } from "arktype"

const 
const MyObj: Type<{
    withDefault: Default<number, 5>;
    key?: number;
}>
MyObj
= type({
"key?": "number", withDefault: "number = 5" }) // { key: undefined, withDefault: 5 } MyObj({ key: undefined, withDefault: undefined }) // { key: number, withDefault: number }
const MyObj: Type<{
    withDefault: Default<number, 5>;
    key?: number;
}>
MyObj
.required()

With false, an explicit undefined at a key with a default is replaced by the default, as a missing key is, so a default can't be undefined itself. Optional and defaultable tuple elements allow undefined the same way. Treating null as missing is tracked in #1283.

As TypeScript's Required does without exactOptionalPropertyTypes, what makes a key or element required drops the undefined it allowed, whether or not it was written: .required(), and a defaulted key or element in .out and .encode.

numberAllowsNaN

number rejects NaN by default. Allow it everywhere with numberAllowsNaN: true, or in one Type with the number.NaN keyword:

const const MaybeNaN: Type<number>MaybeNaN = type("number | number.NaN")

// NaN
MaybeNaN(Number.NaN)

numberAllowsInfinity

number rejects Infinity and -Infinity by default. Allow them everywhere with numberAllowsInfinity: true, or in one Type with the number.Infinity and number.NegativeInfinity keywords:

const const Limit: Type<number>Limit = type("number | number.Infinity")

// ArkErrors: must be a number
type.number(Infinity)

// Infinity
Limit(Infinity)

dateAllowsInvalid

Date rejects an invalid date, like new Date("x"), by default. Allow it with dateAllowsInvalid: true:

config.ts
import { configure } from "arktype/config"

configure({ dateAllowsInvalid: true })
app.ts
import "./config.ts"
import { type } from "arktype"

// Invalid Date
type("Date")(new Date("x"))

jitless

ArkType compiles each Type to optimized validation code using new Function. Where that's blocked, it validates without compiling instead, which is many times slower per call.

Cloudflare Workers allow new Function only as a Worker loads, and a Type compiles once it's used, so a Type first used within a request isn't compiled. To check with compiled code there, precompile your Types, or read a Type's precompilation where it's defined, which compiles it as the Worker loads and adds to its startup.

To turn compiling off yourself, set jitless: true:

config.ts
import { configure } from "arktype/config"

configure({ jitless: true })
app.ts
import "./config.ts"
import { type } from "arktype"

// will not be compiled
const 
const MyObject: Type<{
    foo: string;
}>
MyObject
= type({
foo: "string" })

Configuring jitless globally also skips the check for new Function, which a strict Content-Security-Policy would report as a violation. To validate without generating code and without shipping the parser, precompile your Types when you build.

errors

By default, a failed validation returns an error for each check that failed. errors can return less:

  • "all" (default): every error, at each path that failed
  • "first": the first error validation finds, where it stops
  • "none": one error at the root, whose message is is invalid
config.ts
import { configure } from "arktype/config"
import "arktype/errors"

configure({ errors: "none" })
app.ts
import "./config.ts"
import { type } from "arktype"

const 
const User: Type<{
    name: string;
    age: number;
}>
User
= type({ name: "string", age: "number" })
// ArkErrors: is invalid const
const out: {
    name: string;
    age: number;
} | ArkErrors
out
= User({ name: 5, age: "5" })

"first" and "none" are installed by import "arktype/errors", so a program choosing neither ships neither. Without it, creating a Type configured with either throws.

With "first", which of the data's errors is returned isn't promised, and can differ between a Type and its precompiled validator.

With "none", a failure returns one error with the code "predicate", an empty path and the data. That's the code arktype gives any failure it says nothing more of, like ctx.reject without one, rather than a code of its own, which every switch over codes and every complete locale would have to handle. It's still an instance of type.errors, .assert() throws a TraversalError saying is invalid, and its message isn't localized. A narrow or morph that reads ctx.errors while validating sees each issue added so far written the same way, as is invalid at its own path.

errors can also be set per Scope. It applies where that Scope's Types are called; a Type from another Scope that references them returns errors as its own Scope's errors says.

A precompiled build takes errors as an option.

mutatesInput

By default, a transform copies each object it changes other than a builtin like a Date, so the data you pass is otherwise never written. mutatesInput writes what a Type transforms, its defaults and its morphed values, into the data, which it returns:

  • false (default): copies each object it changes
  • true: writes in place where no other part of the Type can read the write, and otherwise copies
  • "always": writes every transform in place
config.ts
import { configure } from "arktype/config"
import "arktype/mutatesInput"

configure({ mutatesInput: true })
app.ts
import "./config.ts"
import { type } from "arktype"

const 
const User: Type<{
    name: (In: string) => To<string>;
    role: Default<string, "member">;
}>
User
= type({ name: "string.trim", role: "string = 'member'" })
const
const data: {
    name: string;
}
data
= { name: " Ada " }
// true, and data is now { name: "Ada", role: "member" } const const isData: booleanisData = Object.is(User(
const data: {
    name: string;
}
data
),
const data: {
    name: string;
}
data
)

true and "always" are installed by import "arktype/mutatesInput", so a program choosing neither ships neither. Without it, creating a Type configured with either throws.

true always returns what copying would. "always" requires that the data hold no object at two places a transform reaches, and that a Type's functions read or return the data's objects only through the value each is passed, not ctx.root.

The object returned is the data, so it keeps its key order, accessors and inherited keys. Where the data holds one object at two places, a key the Type doesn't declare can hold what the other place wrote. An object a Type deletes undeclared keys from is still copied. A failed validation can leave writes in the objects of its data it found valid.

mutatesInput can also be set for a Scope, whose Types then transform as it says.

A precompiled build takes mutatesInput as an option.

onFail

To throw on every failed validation, or transform its result some other way, configure onFail. Declare it on arktype's ArkEnv so calls are typed to match:

config.ts
import { configure } from "arktype/config"

const 
const config: {
    onFail: (errors: ArkErrors) => never;
}
config
= configure({
onFail: errors => errors.throw() }) declare module "arktype" { interface ArkEnv { onFail: typeof
const config: {
    onFail: (errors: ArkErrors) => never;
}
config
.onFail
} }
app.ts
import "./config.ts"
import { type } from "arktype"

// string, since a failure throws instead of returning ArkErrors
const const data: string | ArkErrorsdata = type.string("foo")

// TraversalError: must be a string
type.string(5)

onFail can also be passed to a scope.

ArkEnv is the arktype module's, not a global, so a declaration on it reaches only the copy of arktype it names. A dependency's copy, like one still on arktype 2, keeps its own keywords and onFail. Declare it in a file that imports or exports something, since a declare module in a file that does neither replaces the module instead. Declare each ArkEnv slot once per app and compose any library types there (for example meta(): LibMeta & AppMeta), since multiple method declarations don't merge.

toJsonSchema

toJsonSchema sets the defaults for .toJsonSchema(), like its target and how to handle what JSON Schema can't express. See JSON Schema.

metadata

Add your own keys to the metadata Types accept by extending ArkEnv:

import { type } from "arktype"

// add this to any module in your project
declare module "arktype" {
	interface ArkEnv {
		meta(): {
			// meta properties should always be optional
			secretIngredient?: string
		}
	}
}

// now types you define can specify and access your metadata
const 
const MrPingsSecretIngredientSoup: Type<{
    broth: "miso" | "vegetable";
    ingredients: string[];
}>
MrPingsSecretIngredientSoup
= type({
broth: "'miso' | 'vegetable'", ingredients: "string[]" }).configure({ secretIngredient: "nothing!" })

toJsonSchema() writes a key you add only if it starts with x-, since JSON Schema has no keyword for it. See Meta.

prototypes

When you .infer a Type, ArkType walks its inferred type to extract special values like morphs, e.g. (In: string) => Out<number>. For some classes that walk is slow or expands the type. Declare them in prototypes to have them treated as opaque:

import { type } from "arktype"

declare module "arktype" {
	interface ArkEnv {
		prototypes(): MySpecialClass
	}
}

class MySpecialClass {}

// Type<MySpecialClass>
const const T: Type<MySpecialClass>T = type.instanceOf(MySpecialClass)

Default scope

Every type(...) call and any scope without its own ambient resolves string references against ArkType's built-in Ark keywords. To override that ambient scope across your program at the type level, declare $() on ArkEnv:

import { type, type Ark } from "arktype"

declare module "arktype" {
	interface ArkEnv {
		$(): type Omit<T, K extends keyof any> = { [P in Exclude<keyof T, K>]: T[P]; }

Construct a type with the properties of T except for those in type K.

Omit
<Ark, "Date">
} } // Type<string> const const Name: Type<string>Name = type("string") const const Bad: Type<never>Bad = type("Date")
TypeScript: 'Date' is unresolvable​

ArkEnv.$ is type-level only — it changes what TypeScript accepts and autocompletes in string definitions, not what exists in ArkType's runtime default scope:

  • Narrowing Ark (with Omit or Pick) needs no runtime setup, since every remaining keyword is already registered.
  • Scopes that pass their own ambient ignore ArkEnv.$.
  • To add custom keywords or replace a keyword's runtime validation, pass ambient to a scope (or export a shared scope's $.type) rather than augmenting ArkEnv.$. To change a built-in keyword's description or error messages globally, use configure({ keywords }).
  • As with onFail and metadata, declare ArkEnv in a file that imports or exports something and declare $() once per app, since multiple method declarations don't merge.