# Technical Documentation: arktypeio/arktype

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/arktypeio/arktype)

### Overview (`ark/aot/README.md`)

# @ark/aot

Constructs a program's arktype definitions at build time, so arktype's parser never ships and nothing compiles at runtime.

Each definition becomes a standalone validator running on `arktype/runtime`, which validates, asserts and implements Standard Schema as the Type it replaces does. A definition the build can't precompile fails the build, naming the file, the definition and the fix. `runtime: "arktype"` ships arktype instead, registering the code it would compile for each Type.

```sh
npm i -D @ark/aot
```

Add its plugin to your bundler. It works with Vite, Rollup, Rolldown, webpack, Rspack, Rsbuild, esbuild, Bun and Farm, and Vitest runs tests through it too:

```ts
// vite.config.ts
import { precompile } from "@ark/aot/unplugin"

export default {
	plugins: [precompile.vite()]
}
```

A program `tsc` builds without a bundler precompiles what it emits:

```sh
tsc && npx arktype-precompile --emit
```

List what the build can't precompile before you switch:

```sh
npx arktype-precompile --check "src/**/*.ts"
```

See [arktype.io/docs/precompile](https://arktype.io/docs/precompile) for everything else, including what a build checks, its options, and the Node, Bun and Turbopack drivers.

---

### Overview (`ark/attest/README.md`)

# Attest

Attest is a testing library that makes your TypeScript types available at runtime, so a test can assert on a value's type, the type errors and completions of an expression, and the type instantiations a block costs.

Assertions work from Vitest, Mocha, Jest or any runner with global setup and teardown hooks.

Benches run as plain scripts. They report how many type instantiations a block contributes, which is deterministic for a given TypeScript version, and how long a call takes.

If you've ever wondered how [ArkType](https://github.com/arktypeio/arktype) can guarantee identical behavior between its runtime and static parser implementations and highly optimized editor performance, Attest is your answer⚡

## Installation

```bash
npm install @ark/attest
```

_Note: This package is still in alpha! Your feedback will help us iterate toward a stable 1.0._

## Docs

See [arktype.io/docs/attest](https://arktype.io/docs/attest) for:

- [Getting started](https://arktype.io/docs/attest) with Vitest, Mocha, Jest and Bun
- [Assertions](https://arktype.io/docs/attest/assertions) for types, values, errors, completions and JSDoc
- [Benches](https://arktype.io/docs/attest/benches) measuring type instantiations and runtime
- [Options](https://arktype.io/docs/attest/options) like `skipTypes` and `typeToStringFormat`
- The [CLI](https://arktype.io/docs/attest/cli) for type performance stats and traces
- [Custom assertions](https://arktype.io/docs/attest/integration) built on the type data attest collects

Please don't hesitate to open a GitHub [issue](https://github.com/arktypeio/arktype/issues/new/choose) or [discussion](https://github.com/arktypeio/arktype/discussions/new/choose) or reach out on [ArkType's Discord](https://arktype.io/discord) if you have any questions or feedback- we'd love to hear from you! ⛵

---

### Overview (`ark/docs/README.md`)

# arktype.io

The docs site: Next.js, statically exported to GitHub Pages.

```bash
pnpm dev # http://localhost:3000
pnpm build # static export to out/
```

- `content/docs` holds the pages as MDX. Each folder's `meta.json` orders its pages: `"---Label---"` starts a sidebar group, `"intro/setup"` lists a page in a subfolder, `"[text](/docs/x#y)"` adds a link, and pages that aren't listed are built but left out of the navigation, search and llms.txt. Folders with `"root": true` are sections.
- `lib/content` turns that into the site without Next: the page tree, frontmatter, heading ids, MDX compilation, highlighting with twoslash, search and redirects. Twoslash results are cached in `node_modules/.cache/ark-docs`.
- `lib/writeMarkdown.ts` writes each page as Markdown at its URL plus `.md`, and the llms.txt files, whenever `next.config.ts` loads.
- `components/mdx/components.tsx` lists every component a page can use.

---

### Overview (`ark/extension/README.md`)

<div align="center">
  <img src="https://arktype.io/image/logo.png" height="64px" />
  <h1>ArkType</h1>
</div>
<div align="center">

[ArkType](https://arktype.io) syntax highlighting and inline errors ⛵

[Install the extension](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkdark)

</div>

We're building a 1:1 validator for TypeScript! Check out our core project [on GitHub](https://github.com/arktypeio/arktype)!

## Features

- syntax highlighting for strings that are part of an ArkType definition



- inline type error summaries optimized for ArkType via [ErrorLens](https://github.com/usernamehw/vscode-error-lens)



See [arktype.io/docs/editor](https://arktype.io/docs/editor) for the settings it changes and the JetBrains and Neovim alternatives.

## Contributing

**Run > Debugger** (`F5` by default) will launch the extension in another window, allowing you to see the effects of your changes on whatever code you open in it.

#### Update syntax highlighting rules

See [injected.tmLanguage.json](/ark/extension/injected.tmLanguage.json)

To determine which scopes need to be changed, you can view scopes applied to any file in VSCode by opening the Command Palette (Ctrl+Shift+P by default) and searching "Developer: Inspect Editor Tokens and Scopes".

Changes to `injected.tmLanguage.json` should be mirrored to [tsWithArkType.tmLanguage.json](./tsWithArkType.tmLanguage.json).

#### Testing tsWithArkType.tmLanguage.json

To test the standalone rules for TS w/ ArkType highlighting, replace `grammars` in `package.json` with the following:

```json
"grammars": {
	"scopeName": "source.ts",
	"language": "typescript",
	"path": "tsWithArkType.tmLanguage.json"
}
```

Be sure to switch back before publishing!

> [!IMPORTANT]  
> You must reload the extension host window to see scope changes reflected

---

### Overview (`ark/fast-check/README.md`)

# @ark/fast-check

Generate [fast-check](https://fast-check.dev) arbitraries from ArkType Types, so property-based tests generate data from the definition you validate with.

```sh
npm i -D @ark/fast-check fast-check
```

```ts
import { arkToArbitrary } from "@ark/fast-check"
import { type } from "arktype"
import * as fc from "fast-check"

const User = type({
	name: "string > 0",
	age: "number.integer >= 0"
})

fc.assert(fc.property(arkToArbitrary(User), user => User.allows(user)))
```

See [arktype.io/docs/fast-check](https://arktype.io/docs/fast-check) for what it can generate, what throws and what it ignores.

---

### Overview (`ark/json-schema/README.md`)

# @ark/json-schema

`jsonSchemaToType` parses a JSON Schema into an ArkType Type:

```ts
import { jsonSchemaToType } from "@ark/json-schema"

const T = jsonSchemaToType({ type: "string", minLength: 5, maxLength: 10 })

T.expression // "5 <= string <= 10"
```

To go the other way, you don't need this package. Every Type has `toJsonSchema()`:

```ts
import { type } from "arktype"

// { $schema: "https://json-schema.org/draft/2020-12/schema", type: "string", maxLength: 10, minLength: 5 }
const schema = type("5 <= string <= 10").toJsonSchema()
```

## Type Safety

`jsonSchema` validates a schema as you write it and infers the type it describes. At runtime, it returns its input unchanged.

```ts
import { jsonSchema } from "@ark/json-schema"

const User = jsonSchema({
	type: "object",
	properties: {
		name: { type: "string" },
		age: { type: "integer", minimum: 0 }
	},
	required: ["name"]
})

// { name: string; age?: number }
type User = typeof User.infer

// TypeScript: minLength must be a non-negative integer (was -1)
jsonSchema({ type: "string", minLength: -1 })
```

`jsonSchemaToType` checks and infers its input the same way.

A schema TypeScript can't see as a literal, like one read from a `.json` file, can be cast with `jsonSchema.as`:

```ts
import { jsonSchema } from "@ark/json-schema"

declare const userJson: object

const User = jsonSchema.as<{ name: string; age?: number }>(userJson)
```

The underlying types are exported as `jsonSchema.infer` and `jsonSchema.validate`.

## How it reads JSON Schema

`jsonSchemaToType` reads a schema with [`arksets`](https://github.com/arktypeio/arktype/tree/main/ark/sets)' `parse`, so the Type accepts exactly what a JSON Schema 2020-12 validator accepts, except that lengths count UTF-16 code units where JSON Schema counts code points (draft-07 forms are read too). `format` is an annotation, as the spec defaults to. Keywords that can't be read exactly, like a remote `$ref` or `unevaluatedProperties`, throw with their JSON Pointer.

## Docs

See [arktype.io/docs/json-schema](https://arktype.io/docs/json-schema) for:

- [From JSON Schema](https://arktype.io/docs/json-schema/from-json-schema): `jsonSchemaToType`, typing its result and `JsonSchemaScope`
- [Keyword support](https://arktype.io/docs/json-schema/support): which keywords are checked, which throw and which are ignored
- [To JSON Schema](https://arktype.io/docs/json-schema/to-json-schema): `toJsonSchema()` and its options

---

### Overview (`ark/regex/README.md`)

# arkregex

A drop-in replacement for `new RegExp()` with types

## Usage

The `regex` function creates a `Regex` instance with types for `.test()`, `.exec()` and more, statically parsed from native JS syntax:

```ts
import { regex } from "arkregex"

const ok = regex("^ok$", "i")
// Regex<"ok" | "oK" | "Ok" | "OK", { flags: "i" }>

const date = regex("^(\\d{4})-(\\d{2})-(\\d{2})$")
// Regex<`${number}-${number}-${number}`, { captures: [`${number}`, `${number}`, `${number}`] }>

const email = regex("^(?<name>\\w+)@(?<domain>\\w+\\.\\w+)$")
// Regex<`${string}@${string}.${string}`, { names: { name: string; domain: `${string}.${string}`; }; ...>
```

All you need to get started is `pnpm install arkregex` (or the equivalent for your package manager of choice) 🎉

Performs best with TS 5.9+

### Features

- **Types**: Infers string types for your existing regular expressions, including positional and named captures
- **Syntax**: Parses the [syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions) `new RegExp()` accepts, including named groups, lookarounds, backreferences, modifiers and Unicode properties
- **Safety**: Syntax errors like referencing a group that doesn't exist are now type errors
- **Zero Runtime**: Improves your type safety without impacting your bundle size

## Docs

See [arktype.io/docs/regex](https://arktype.io/docs/regex) for:

- [Inference](https://arktype.io/docs/regex/inference) of patterns, captures and flags
- [Errors](https://arktype.io/docs/regex/errors) reported for invalid syntax
- [Types](https://arktype.io/docs/regex/types) like `Regex`, `regex.infer` and `regex.as`
- [ArkType](https://arktype.io/docs/regex/arktype) integration
- [FAQ](https://arktype.io/docs/regex/faq)

---

### Overview (`ark/schema/README.md`)

# @ark/schema

Underlying schema language parsed from arktype syntax.

The parts of ArkType's type system that exist in TS (i.e. not runtime-only constraints like bounds, divisors, custom predicates, morphs etc.) are structured like this:

- Union: a set of intersections
- Intersection: a set of a basis and constraints
- Basis: this is the base type to which refinements like props are applied. It is one of three things, getting narrower as you move down the list:
  - Domain: `"string" | "number" | "bigint" | "object" | "symbol"` parallels built-in TS keywords for non-enumerable value sets
  - Proto: Must be an `instanceof` some class (implies domain `"object"`)
  - Unit: Must `===` some value (can be intersected with any other constraint and reduced to itself or a disjoint)
- Constraint: an individual condition that must be satisfied:
  - Required: must have a specified literal string or symbol key and a value that conforms to a specified union or intersection
  - Optional: Required conditions met or the specified key is not present
  - Index: all keys that satisfy an index type must have values satisfying the corresponding value type

In this system, `L` extends/subtypes/is assignable to `R` if and only if the intersection `L & R` is equal to `L`.

## Docs

`@ark/schema` isn't semver-stable. See [arktype.io/docs/internals](https://arktype.io/docs/internals) for its node kinds, schemas, `rootSchema` and `schemaScope`, and how it relates to `arksets` and `arktype`.

---

### Overview (`ark/sets/README.md`)

# arksets

Set algebra for schemas in any format. arksets reads an arktype Type, a Standard JSON Schema (e.g. zod) or a JSON Schema as the set of values it accepts, relates and combines those sets with arktype's algebra, and writes them back out as JSON Schema.

```ts
import { discriminate, intersect, isSubset, toJsonSchema } from "arksets"
import { z } from "zod"

const v1 = z.object({ id: z.string(), age: z.number().int().min(0) })
const v2 = z.object({ id: z.string(), age: z.number().optional() })

// v2 is backwards compatible: it accepts everything v1 did
isSubset(v1, v2) // true
isSubset(v2, v1) // false: v2 accepts { id: "a" }

intersect(v2, { properties: { age: { maximum: 120 } } }).expression // "{ id: string, age?: number <= 120 }"
toJsonSchema(v2) // { $schema: "https://json-schema.org/draft/2020-12/schema", type: "object", properties: { id: { type: "string" }, age: { type: "number" } }, required: ["id"] }

const Event = z.discriminatedUnion("kind", [
	z.object({ kind: z.literal("click"), x: z.number() }),
	z.object({ kind: z.literal("key"), key: z.string() })
])
discriminate(Event) // { path: ["kind"], kind: "unit", cases: [{ value: "key", branches }, { value: "click", branches }], default: null }
```

Relations are sound for what each schema is read as: `true` is a proof, and `false` means it couldn't be proven, e.g. through `not` or `uniqueItems`. A Type is read exactly and a JSON Schema as [below](#json-schema). A Standard JSON Schema is read as the JSON Schema it writes, so what that can't express, like zod's refinements, transforms and `undefined`, is invisible, and `true` proves the relation only for those JSON Schemas: `isSubset(z.string(), z.string().refine(s => s === "x"))` is `true`.

## API

Every argument is a `Schema`: a Root (an `@ark/schema` node, which every arktype Type is), a Standard JSON Schema, or a JSON Schema object or boolean.

A Standard JSON Schema is a schema whose `~standard` has `jsonSchema`, e.g. from zod 4.2.0 or later. Pass any other library's schema as its JSON Schema, e.g. `z.toJSONSchema(schema)` before zod 4.2.0. Anything else throws a `ParseError`, as does a Standard JSON Schema whose `~standard.jsonSchema` throws, like zod's for `z.date()`, with the library's error as its `cause`.

| function                      | returns                                                           |
| ----------------------------- | ----------------------------------------------------------------- |
| `parse(schema, options?)`     | the Root of the values `schema` accepts                           |
| `isSubset(l, r)`              | whether every value `l` accepts, `r` accepts                      |
| `isEqual(l, r)`               | whether `l` and `r` accept the same values                        |
| `isDisjoint(l, r)`            | whether no value is accepted by both                              |
| `intersect(...schemas)`       | a Root of what every schema accepts (`never` if they're disjoint) |
| `union(...schemas)`           | a Root of what any schema accepts, without subsumed branches      |
| `discriminate(schema)`        | how a union's branches are told apart, or `null`                  |
| `toJsonSchema(schema, opts?)` | the JSON Schema of `schema`                                       |

Roots validate (`root(data)`, `root.allows(data)`), print (`root.expression`) and can be passed back in. A Standard Schema's read is cached; a JSON Schema is plain data, so it's read on every call.

`parse` reads a schema's input by default, or its output with `{ io: "out" }`. A JSON Schema's `#/...` refs resolve against the schema itself, or against `{ root: document }`, e.g. an OpenAPI document.

## Comparing arktype Types with JSON Schema

An arktype object can also be an array, and a JSON Schema object can't, so an arktype Type is compared by its own semantics. Compare its `.toJsonSchema()` to use JSON's:

```ts
import { isSubset } from "arksets"
import { type } from "arktype"
import { z } from "zod"

const User = type({ name: "string" })
const ZodUser = z.object({ name: z.string() })

isSubset(ZodUser, User) // true
isSubset(User, ZodUser) // false: User allows Object.assign([], { name: "" })
isSubset(User.toJsonSchema(), ZodUser) // true
```

## JSON Schema

A Root read from a JSON Schema accepts exactly what a 2020-12 validator accepts, except that lengths count UTF-16 code units, with ajv as the tiebreaker. Every keyword applies, and a type's keywords constrain only that type, so `{ minimum: 5 }` accepts `"foo"`. draft-07 forms (`items` arrays, `additionalItems`, `definitions`, `dependencies`) are read too, and a `$schema` of draft-07 or earlier ignores a `$ref`'s siblings.

- `format` is an annotation, as the spec defaults to. arktype writes a `pattern` beside each format, so its JSON Schema reads back equal.
- A `pattern` may also be a `RegExp`, read with its own flags.
- Lengths count UTF-16 code units, as arktype's bounds do, where JSON Schema counts code points.
- A `$ref` that isn't a JSON Pointer into its document, `$dynamicRef`, `unevaluatedProperties` and `unevaluatedItems` throw with their JSON Pointer, as does a keyword whose value is invalid.

## The engine

Importing `arksets` also installs the algebra `@ark/schema` uses to reduce nodes and discriminate unions as they're parsed, and to implement `.toJsonSchema()` and relational methods like `.and()`, `.extends()` and `.keyof()`. arktype installs it from `arksets/internal`, so arksets' public API stays out of arktype's bundle.

Without it, `@ark/schema` parses and validates unreduced nodes and undiscriminated unions, and relational methods and `.toJsonSchema()` throw. Parsing a schema whose validation depends on reduction throws as well: a tuple that bounds its length, an unordered union with a transforming branch, an optional prop under `exactOptionalPropertyTypes: false`, or an index signature keyed by anything other than `string`, `symbol` or `string | symbol`.

See [arktype.io/docs/internals/sets](https://arktype.io/docs/internals/sets) for what works without it.

---

### Overview (`ark/themes/README.md`)

<div align="center">
  <img src="https://arktype.io/image/logo.png" height="64px" />
  <h1>ArkThemes</h1>
</div>

<div align="center">

A collection of themes with special highlighting for TypeScript generics ⛵

Created with love by the [ArkType](https://arktype.io) team 🥰

</div>

### Dark



### Light

---

### Overview (`ark/type/README.md`)

<h1 align="center">ArkType</h1>
<h3 align="center"><i>TypeScript's 1:1 validator, optimized from editor to runtime</i></h3>

ArkType validates data at runtime with definitions written in TypeScript's own syntax.

```sh
npm install arktype
```

```ts
import { type } from "arktype"

const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

const out = User({ name: "Alan", age: -1 })

if (out instanceof type.errors) {
	// age must be non-negative
	console.error(out.summary)
} else {
	// { name: string; age?: number }
	console.log(out.name)
}
```

To ship less, [precompile](https://arktype.io/docs/precompile) your Types when you build: each becomes a validator with only the checks it needs, so arktype's parser never ships.

## Docs

- [arktype.io](https://arktype.io/docs/intro/setup)
- [Using ArkType with coding agents](https://arktype.io/docs/agents): the skill (`npx skills add arktypeio/arktype`) and Markdown docs at [arktype.io/llms.txt](https://arktype.io/llms.txt)

## Contributions

We accept and encourage pull requests from outside ArkType. Planned work is tracked in [this GitHub project](https://github.com/orgs/arktypeio/projects/4).

Depending on your level of familiarity with type systems and TS generics, some parts of the codebase may be hard to jump into. That said, there's plenty of opportunities for more straightforward contributions. We'd generally recommend starting with one of these issues labeled [external-contributor-friendly](https://github.com/orgs/arktypeio/projects/4/?filterQuery=label%3A%22external-contributor-friendly%22).

If you're planning on submitting a non-trivial fix or a new feature, please [create an issue first](https://github.com/arktypeio/arktype/issues/new) so everyone's on the same page. The last thing we want is for you to spend time on a submission we're unable to merge.

When you're ready, check out our [guide](https://github.com/arktypeio/arktype/blob/main/.github/CONTRIBUTING.md) to get started!

## License

This project is licensed under the terms of the
[MIT license](https://github.com/arktypeio/arktype/blob/main/LICENSE).

## Code of Conduct

We will not tolerate any form of disrespect toward members of our community. Please refer to our [Code of Conduct](https://github.com/arktypeio/arktype/blob/main/.github/CODE_OF_CONDUCT.md) and reach out to david@arktype.io immediately if you've seen or experienced an interaction that may violate these standards.

## Sponsorship

We've been working full-time on this project for multiple years and it means a lot to have the community behind us.

If the project has been useful to you and you are in a financial position to do so, please chip in via [GitHub Sponsors](https://github.com/sponsors/arktypeio).

Otherwise, consider sending me an email (david@arktype.io) or [message me on Discord](https://arktype.io/discord) to let me know you're a fan of ArkType. Either would make my day!

### ArkSponsors ⛵

<table>
    <tr>
        <th>get-convex</th>
    </tr>
    <tr>
        <td>
            <a href="https://github.com/get-convex"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/get-convex"
            /></a>
        </td>
    </tr>
</table>

### Sponsors 🥰

<table>
    <tr>
        <th>mewhhaha</th>
        <th>jahands</th>
        <th>Phalangers</th>
        <th>WilliamConnatser</th>
        <th>JameEnder</th>
    </tr>
    <tr>
        <td>
            <a href="https://github.com/mewhhaha"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/mewhhaha"
            /></a>
        </td>
        <td>
            <a href="https://github.com/jahands"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/jahands"
            /></a>
        </td>
        <td>
            <a href="https://github.com/Phalangers"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/Phalangers"
            /></a>
        </td>
        <td>
            <a href="https://github.com/WilliamConnatser"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/WilliamConnatser"
            /></a>
        </td>
        <td>
            <a href="https://github.com/JameEnder"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/JameEnder"
            /></a>
        </td>
    </tr>
    <tr>
        <th>tylim88</th>
        <th>tpetry</th>
        <th>braden-w</th>
    </tr>
    <tr>
        <td>
            <a href="https://github.com/tylim88"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/tylim88"
            /></a>
        </td>
        <td>
            <a href="https://github.com/tpetry"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/tpetry"
            /></a>
        </td>
        <td>
            <a href="https://github.com/braden-w"
                ><img
                    height="64px"
                    src="https://avatars.githubusercontent.com/braden-w"
            /></a>
        </td>
    </tr>
</table>

---

### Overview (`ark/repo/bench/external/README.md`)

# External benchmarks

The site's speed and size claims outside the homepage's own benchmark
(`ark/docs/lib/claims.ts`) come from runs of other projects' benchmarks. This
directory holds what those runs need beyond the projects themselves, and the
plan they follow, written before the release candidate's data existed.

## Reproduce

Every row on the leaderboard comes from one of these commands, run from a
clean checkout after `pnpm i && pnpm build`, on Linux with `perf` and
`taskset`:

```sh
NODE24=<node 24.14.1> NODE26=<node 26.12.1> pnpm benchExternal <suite>
pnpm benchExternal <suite> --latest # its rivals at their 2026-10-24 releases
pnpm benchExternal <suite> --newest # its rivals at their newest releases, kept in results/newest/
pnpm benchValidate # the homepage's speed rows
pnpm benchSize # the homepage's app sizes
pnpm benchImport # the homepage's cold start
```

`<suite>` is `moltar`, `sb`, `sury`, `ata`, `form`, `startup`, `size` or
`all`, where `size` is the form and the download and bundle rows of
schemabenchmarks.dev and Sury, without counting anything.
`benchExternal` clones each external suite at the commit its rows were
counted on into `out/clones/`, installs it from its own lockfile, adds
ArkType as "How each new suite is run" describes, counts every arm into
`out/fresh/`, and prints the standings over the fresh rows beside the
published ones. Here `all` takes about 90 minutes: schemabenchmarks.dev 45,
ata's 30, moltar's 10, Sury's 3, the form and `startup.ts` one each. If
ttsc's first Go build of typia's plugin fails, run the suite again.

The published rows were counted on an Intel i7-11700 (8 cores, 16 threads)
under WSL2 (Linux 6.18, perf 6.18), pinned to cores 10-15, on Node 24.14.1
for moltar's, Sury's and ata's suites and `startup.ts`, 26.12.1 for
schemabenchmarks.dev (its `.node-version`) and 25.2.1 for the homepage's
benchmark.

**Weekly.** `.github/workflows/leaderboard.yml` runs
`pnpm benchExternal size --newest` every Monday on a GitHub-hosted runner:
ArkType at main, each rival at its newest release. `--newest` keeps the run
in `results/newest/`, with each suite's commit, date and installed versions
in `run.json`, and rewrites `ark/docs/lib/bench/leaderboard.json`, where
each rival keeps its smaller bundle of its pinned, 2026-10-24 and newest
installs, ArkType's rows are the run's and `measured` is the run's date,
which the site prints as "Standings as of". The job pushes nothing: it
checks the site's claims against the new standings
(`ark/docs/lib/bench/headline.ts`), shows the standings in its summary and
uploads the run as the `leaderboard` artifact. If a claim isn't backed, such
as a lead lost by more than the tie band, it opens an issue mentioning
@ssalbdivad, or updates the open one, with the claims before and after, the
standings and the run's link, and the run fails. Publishing new standings is
a rerun by hand and a commit. The speed and startup suites count
instructions with perf, and hosted runners don't expose hardware counters,
so they're rerun by hand on a machine that does, with `--newest` keeping
them the same way.

**Expected variance.** Load doesn't move an instruction count, but a run's
tiering and garbage collection do. Every suite rerun from a clean clone
(2026-10-24) against the committed rivals' counts: moltar's 62 arms, 61
within 1% and the last 3%; schemabenchmarks.dev's valid-data arms, 96% of
207 within 3% and all within 11%, while arms that build error objects move
up to 40% (typia's invalid createValidate 0.59x, its invalid Standard Schema
1.47x); Sury's parse arms within 3%, its build arms, which allocate, up to
18%; ata's 119 arms, 94% within 3%, the worst 1.44x (ata's own errors on the
config body). Every bundle size reproduced to the byte, and no top-two
score moved by more than 0.009 (Typia's startup, 2.815 to 2.824). On another CPU or Node build, expect each
arm's count to shift by a few percent and ratios by less. The homepage's
speed rows are wall clock, so compare their ratios, not their nanoseconds.

## The plan

One run, published whatever it shows. Every published speed sentence is a
test fixed here first.

**Builds.** The release candidate, built once, on Node 24.14.1.

- B1: the default build, `{}`, as a production build.
- B2: the `"smallest"` preset, as a production build: the size build.
- dynamic: plain `type()`.

The production builds are esbuild builds with the `"production"` condition.
External projects are pinned: moltar's typescript-runtime-type-benchmarks at
499f3fb, with its own installs; schema-benchmarks at f1e6e8e; arktype 2.2.9
from npm (`moltar/v2`).

**C, deterministic.** No statistics. A count holds if max/min ≤ 1.001 over 3
reps.

1. Instructions per call, in benny's call shape (`moltar/cjs/child.ts`), for
   moltar's four cases × {B1, B2, dynamic}, and the libraries ranked near
   ArkType on moltar's published results (`arms.ts`). Also 2.2.9 on the strict
   cases, and schema-benchmarks' valid-data validation for B1 and dynamic
   (`sb/`).
2. Bundle sizes of valibot.dev's login form as written, with its messages
   (`login/size.ts`): B1, B2, default+lean (B1 with the validator's members
   off), dynamic, Valibot, Zod Mini, Zod, and ajv's standalone code.
3. `pnpm benchValidate`, which drives the homepage's benchmark: 150 rounds
   plus one replication.

**H, wall clock.** One run of 30 passes (`wall.ts`). Each pass runs every arm
once, in a random order, each in its own process pinned to cores 10-15. A
pass starts only while the 1-minute load is under 4. The family is Holm over
four hypotheses at α 0.05 (thresholds 0.0125, 0.0167, 0.025, 0.05). H1 and H2
are intersection-union tests: the p is the largest over every rival within
25% of B1's instruction count.

| #   | hypothesis                                                                           | pairs                                                                                        | test                                              |
| --- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| H1  | B1 is faster than every rival on moltar's parseSafe                                  | @ts-runtypes, typia, ata-aot, ata, rescript-schema, @sx3/gate                                | two-sided sign test per pair, p = max             |
| H2  | B1 is faster than every rival on moltar's assertLoose                                | ts-runtime-checks, ts-auto-guard, type-predicate-generator, TypeBox AOT, typia, @ts-runtypes | same                                              |
| H3  | dynamic is not slower than B1 by more than 5% on schema-benchmarks' valid validation | dynamic vs B1                                                                                | one-sided sign test on per-pass dynamic/B1 < 1.05 |
| H4  | dynamic is more than 5x faster than 2.2.9 on moltar's assertStrict                   | dynamic vs 2.2.9                                                                             | one-sided sign test on per-pass ratio < 0.2       |

**Decision rules.**

- With 30 passes, the first Holm step needs 23 of 30 (p 0.0052).
- No reruns, and no pair added or dropped after the data.
- If H1 or H2 fails, its sentence falls back to what C1 proves: the fewest
  instructions per call on that case, in our runs.
- If H3 fails, the claim that dynamic ArkType is as fast as precompiled goes.
- If H4 fails, the strict speedup over 2.2 is stated in instructions, from
  C1.
- Every pass's ratios are published with the run.

## Running it

From the repo root, after `pnpm build`, with perf, a moltar clone whose
compiled cases are built, and a schema-benchmarks clone with its dependencies:

```sh
npm i --prefix ark/repo/bench/external/moltar/v2
node ark/repo/bench/external/moltar/build.ts
SB=<schema-benchmarks> SB_MODULES=<its node_modules> node ark/repo/bench/external/sb/bundle.ts
MOLTAR=<moltar> NODE24=<node 24.14.1> node ark/repo/bench/external/arms.ts
node ark/repo/bench/external/count.ts <counts.json> 3
node ark/repo/bench/external/wall.ts <wall.json> 30
node ark/repo/bench/external/stats.ts <wall.json>
node ark/repo/bench/external/login/size.ts <sizes.json>
```

## The release candidate's run

`results/` holds the run at c42ee008c, on a shared 16-core machine: the arms
as run (`arms.json`), the counts (`counts.json`, `counts.md`), the sizes
(`login.json`, esbuild 0.28.2) and the wall-clock passes (`wall.json`, with
every pass's ratios in `wall.md`). The wall run took 30 passes from 06:46 to
07:17 UTC; the gate held two passes back at loads of 7.2 and 5.0, and pass 3
ended at 5.2.

| test | result                                                                                                                                                                               |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| H1   | **fails** (p 1): B1 beat @ts-runtypes, typia, ata-aot and ata in 26-28 of 30 passes, but rescript-schema and @sx3/gate were faster in 21 and 24 (B1 took 1.04x and 1.05x their time) |
| H2   | holds (p 0.0052 ≤ 0.0167): its closest pair, ts-runtime-checks, 23 of 30, 0.93x                                                                                                      |
| H3   | holds (p 0.0081 ≤ 0.025): dynamic/B1 0.998, under 1.05 in 22 of 30                                                                                                                   |
| H4   | holds (p 9.3e-10 ≤ 0.0125): dynamic/2.2.9 0.078, under 0.2 in 30 of 30                                                                                                               |

C1 holds its ranks: B1 takes the fewest instructions on parseSafe (189 vs
@ts-runtypes 209, typia 213) and assertLoose (66 vs ts-runtime-checks 74).
The parseSafe cells miss the 1.001 gate by up to 0.0023 (0.3 instructions),
which reorders nothing. 2.2.9's strict counts vary by 14-16% between reps, so
their ratios to dynamic span 11.2x to 13x. C2: B2 is 1312 B gzipped, Valibot 1547.

At 3eb166a9c, a fix that keeps union merges from dropping branch descriptions
grew dynamic ArkType's login bundle to 80041 B gzipped
(`results/login-3eb166a9c.json`). Every other size is unchanged.

At be45edabb, dynamic ArkType's login bundle is 80672 B gzipped and B2 is
1313 (`results/login-be45edabb.json`). Every other size is unchanged.

## The release's deterministic re-run

At the release, f29b8d153, `results/login-f29b8d153.json` holds the login
form's sizes: B2 is 1315 B gzipped (Valibot 1547), B1 1779 and dynamic
ArkType 82263. `results/counts-a306152ce.{json,md}` holds C1 at a306152ce,
whose builds f29b8d153 doesn't change (it differs only in how a scope caches
a keyword bound to it). B1 still takes the fewest instructions on parseSafe
(184, from 189; @ts-runtypes 209, typia 213) and assertLoose (66;
ts-runtime-checks 74). Dynamic ArkType's parseSafe fell from 262 to 216, and
B2's assertLoose rose from 71 to 3220, since the size build now checks with
small shared checkers. 2.2.9's strict counts vary by 20-26% between reps, so
dynamic's ratios to them span 10.2x to 17.1x. The wall-clock run above is
still the release candidate's.

## The release's wall-clock run

`results/wall-f29b8d153.{json,md}` is the same plan's run at the release,
f29b8d153, with the same arms and builds (B1, B2 and schema-benchmarks' B1
bundle are byte-identical to a306152ce's): 30 passes from 09:26 to 10:11 UTC,
starting at 1-minute loads of 1.0-4.0, with pass 8 ending at 6.3. Every
hypothesis holds.

| test | result                                                                                                                                      |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| H1   | holds (p 8.7e-7 ≤ 0.0167): every pair 28-29 of 30; rescript-schema 0.90x, @sx3/gate 0.92x, @ts-runtypes, typia, ata-aot and ata about 0.83x |
| H2   | holds (p 0.0014 ≤ 0.05): its closest pair, ts-runtime-checks, 24 of 30, 0.94x                                                               |
| H3   | holds (p 0.00072 ≤ 0.025): dynamic/B1 0.999, under 1.05 in 24 of 30                                                                         |
| H4   | holds (p 9.3e-10 ≤ 0.0125): dynamic/2.2.9 0.074, under 0.2 in 30 of 30                                                                      |

At 89510709d, a leaner error writer shrank B2's login form to 1313 B gzipped
(`results/login-89510709d.json`); every other size is unchanged.

At 5acd85130, dynamic ArkType's login bundle is 82946 B gzipped
(`results/login-5acd85130.json`), from 82263 at f29b8d153: checking UUIDs, IP
addresses and ISO dates by their char codes added 779, and declaring arkregex
free of side effects took 17 back (`results/login-1e74181e4.json`, before that,
has 82965). Its precompiled rows are pruned by usage and assert the form
(1edc2a765): the default build (B1) is 1140 B and the `"smallest"` preset
(B2) is 1037 B. The docs' size chart and `loginSize` cite this file, with B1 as
ArkType's bar. Its earlier 1313 was B2 at 89510709d, before builds pruned by
usage, as B1's 1779 was. The 1158 in "Best average" is the default build of
`forms/arktype.ts`, the same form with the same esbuild settings, which
exports a function that asserts where `login/arktype.ts` asserts once.

At 20710020e (`results/login-20710020e.json`), the default build is 1007 B
gzipped, the `"smallest"` preset 978 and dynamic ArkType 89751; Valibot 1547,
Zod Mini 5127 and Zod 25058 are unchanged. Every other ArkType row was
measured again on the same commit (`results/arktype-20710020e.json`,
`results/startup-20710020e-node24.json`, Typia included, and
`results/newest/`, every rival at its newest release of 2026-11-06), at
1-minute loads of 6 to 12.

## The smallest preset's speed

`results/smallest-3f6c3c32b.json` holds B2, the `"smallest"` preset, on
moltar's four cases at 3f6c3c32b, beside B1 and moltar's own Valibot and Zod
cases (`cases/valibot.ts` and `cases/zod.ts` at 499f3fb), on Valibot 1.5.0
and Zod 4.6.7. It was counted on 2026-11-06 from 14:08 to 14:11 UTC, at
1-minute loads of 18 to 20, by `count.ts` over 3 reps on Node 24.14.1,
pinned to cores 10-15, of the arms `moltar/smallest.ts` writes. Each runs
`moltar/cjs/child.ts`'s call shape on moltar's data, without a clone of
moltar's. On B1 it counts 217, 337, 69 and 332 instructions where moltar's
harness counted 184.6, 339, 66 and 332 at 20710020e, whose B1 counts the
same as 3f6c3c32b's here, so its rows can differ from that harness's by up
to 18%. Medians, in instructions per call:

| case         | B1 (default) | B2 (`"smallest"`) | Valibot | Zod 4 |
| ------------ | -----------: | ----------------: | ------: | ----: |
| parseSafe    |          217 |              8605 |    8299 |  1086 |
| parseStrict  |          337 |              4451 |    9533 |  2171 |
| assertLoose  |           69 |              3179 |    8218 |  2087 |
| assertStrict |          332 |              4402 |    9450 |  2101 |

B2 takes 4% more instructions than Valibot on parseSafe and 2.1-2.6x fewer
on the other three, while Zod 4 takes 1.5-7.9x fewer than B2 and B1 13-46x
fewer. Zod's counts vary by up to 9% between reps, every other arm's by
under 1%. From the repo root, after `pnpm build`:

```sh
node ark/repo/bench/external/moltar/build.ts
NODE24=<node 24.14.1> node ark/repo/bench/external/moltar/smallest.ts
COUNT_ARMS=ark/repo/bench/external/out/smallestArms.json \
	node ark/repo/bench/external/count.ts <out.json> 3 2
```

These replace B2's rows in `counts.json` (c42ee008c) and
`counts-a306152ce.json`, which predate ca800dff2. From it, a checker can
delete or reject a key it doesn't declare, so B2 writes `tSafe` and
`tStrict` as checkers too, where it had compiled them, as it had compiled
every Type at c42ee008c.

## The homepage's apps

`bench/size.ts` sizes each of the homepage's apps as `bench/bundle.ts`
bundles it: the app's exports, minified by esbuild with the `"production"`
condition and gzipped. Every library is bundled the same way, as a
production build ships. At e9e6ebc10 only the `"smallest"` preset's bundles
had the condition, so the default build was sized as a development build,
without the usage pruning a production build does: login 1809 B gzipped,
moltar 1885, shop 9445 and saas 16030. As production builds they are 1649,
1680, 7057 and 12374. No other library's bundle changes.

## Cold start

`startup.ts` counts what a fresh process spends from just before it imports
an app's bundle to just after its first validation of valid data returns:
perf's user-space instructions over every thread, with no compile cache.
Each app is bundled as request handlers read it, one handler per validator
returning the data or the issues, with bench/bundle.ts's esbuild settings as
a production build. ArkType is precompiled with each of `STARTUP_BUILDS`'
options, so a production build prunes what the handlers don't read. The
apps are the homepage's login, moltar and shop, and valibot.dev's login form
(`startup/form`, against the libraries that write it). A baseline bundle
that validates nothing gives the cost of loading any module; counts less it
are what a library adds.

The plan, fixed before any count: 20 rounds, each running every arm once in a
rotated order. An ArkType build has the fewest instructions on an app if it
has fewer than every other library in a two-sided sign test paired by round
at p < .05. A claim needs Node 24 and 25 to agree, and a wall-clock sentence
needs the same test on 30 rounds of `STARTUP_WALL=1`, timed one process at a
time while the 1-minute load is under 4.

Every bundle's path has the same length and every process runs in `/`: the
first run, from `ark/repo` with bundles named by library, found Node's loader
costing about 0.37M more instructions past some length of directory plus file
name. Only ajv's shorter names stayed under it, so that run favored ajv; it
is superseded.

From the repo root, after `pnpm build` and bench/generateTypia.ts:

```sh
STARTUP_BUILDS='{"default":{},"optimizeErrors":{"optimizeErrors":"size"}}' \
	STARTUP_NODE=<node> node ark/repo/bench/external/startup.ts <out.json> 20
```

At 4fd880692 (`results/startup-4fd880692-node{24,25}.json`, builds `default`,
`optimizeErrors: "size"` as `oe`, `oe` with `lazy: false` and `"smallest"`),
every build has the fewest instructions on the form, 20 of 20 against each
library on both Nodes, and on the login app, 19 or 20 of 20 against all
seven: `oe` adds 1.28M on Node 24 where ajv adds 1.86M, Valibot 2.35M and
Typia 2.43M (gross 4.95M against ajv's 5.52M). On moltar Typia adds fewer
(1.16M against `oe`'s 1.39M), and on shop Valibot does (12.26M against
14.29M), except against `"smallest"` (9.09M). No wall-clock run yet.

The published rows are the default build's at 781130da3
(`results/startup-781130da3-node24.json`): the fewest instructions on every
app against every library run, 20 of 20 each. Net of the baseline, the form
is 0.91M against Valibot's 2.37M, the login app 0.89M against ajv's 1.86M,
moltar 0.95M against ajv's 1.43M and shop 9.95M against Valibot's 12.26M.
Typia wasn't run there, since its generated validators
(`bench/generateTypia.ts`) weren't built first, so that run's rows and the
board's `startup.ts` rows lack it; at 90d510484 it was the closest library on
moltar, 1.16M to 1.05M, 19 of 20.

## Best average

The headline's superlatives come from a rule, written before any average was
computed: a library is the fastest, the quickest to start or the smallest if
it has the best average in that category across the public benchmarks that
qualify. Since 2026-10-25 the headline counts only the independent ones:
other projects' suites, and valibot.dev's login form, whose code is Valibot's
though we wrote it in each library and size it with our script ("The
headline's suites"). The full board, every suite, is published beside it. In every category, an average within 5% of
the best counts as first ("Ties"), since one release can move a result by about that much. The size suites are rerun every week at each library's newest release
("Weekly" under "Reproduce"). The current standings come first, then the
rule, then each earlier average as its record.

### Current standings: ArkType at 781130da3, rivals at their releases of 2026-10-24 and 2026-10-27

Thirteen suites qualify: 5 for speed (75 rows), 4 for startup (9) and 4 for
size (7). `ark/docs/lib/bench/leaderboard.json` holds every row, and
`ark/docs/lib/claims.ts` computes the standings from it. The size rows
measure production Vite, Rollup, Rolldown or esbuild builds, which prune
validators by usage; webpack, Rspack and Turbopack don't
([`prune`](https://arktype.io/docs/precompile/options#prune)), so their
bundles are larger.

| category | suite                                       | rows | measure                          | run by                   |
| -------- | ------------------------------------------- | ---- | -------------------------------- | ------------------------ |
| speed    | moltar's typescript-runtime-type-benchmarks | 4    | instructions per call            | moltar                   |
| speed    | the homepage's benchmark                    | 32   | median ns per call               | us                       |
| speed    | schemabenchmarks.dev                        | 26   | instructions per call            | Open Circle              |
| speed    | Sury's schema benchmark                     | 1    | instructions per call            | Sury's author            |
| speed    | ata's validator-benchmarks                  | 12   | instructions per document        | ata's author             |
| startup  | `startup.ts`                                | 4    | instructions beyond the baseline | us                       |
| startup  | the homepage's cold start                   | 3    | median ms                        | us                       |
| startup  | schemabenchmarks.dev's initialization       | 1    | instructions per call            | Open Circle              |
| startup  | Sury's build and parse once                 | 1    | instructions per call            | Sury's author            |
| size     | valibot.dev's login form                    | 1    | gzipped bytes                    | us, and Valibot's author |
| size     | the homepage's apps                         | 4    | gzipped bytes                    | us                       |
| size     | schemabenchmarks.dev's download             | 1    | gzipped bytes                    | Open Circle              |
| size     | Sury's schema bundled as a check            | 1    | gzipped bytes                    | Sury's author            |

ArkType's instruction-count and size rows are measured at 781130da3, by
claim-all's finalrun steps: `results/arktype-781130da3.json` and
`results/startup-781130da3-node24.json`. The form, schemabenchmarks.dev's
download and Sury's check score `results/newest/` instead, sized again at
2c1a6a86e, whose runtime is 781130da3's, with every rival at its newest
release of 2026-10-27. The homepage's wall-clock rows in `benchData.json`
weren't rerun: its scenarios stay 808927feb's.

Each rival arm is the faster of two counts, at its suite's pins and at the
latest releases ("Versions" below).

The headline's standings, over the 9 independent suites: 4 for speed (43
rows), 2 for startup (2) and 3 for size (3).

| category | 1                    | 2              | 3              |
| -------- | -------------------- | -------------- | -------------- |
| speed    | ArkType 1.083        | ata 1.254\*    | paseri 2.140\* |
| startup  | zod-compiler 1.000\* | paseri 1.001\* | ArkType 1.002  |
| size     | ArkType 1.176        | Typia 1.256\*  | ajv 1.317\*    |

\* ranked on half to three quarters of the category's suites. ArkType's
speed average is 13.7% lower than the next best's and its size average 6.3%
lower, figured as `claims.ts` states them (1 − ArkType's / the next best's).
Startup's three are within 0.2%, on schemabenchmarks.dev's
initialization alone for zod-compiler and paseri, so ArkType counts as first,
within the 5% that does. Both startup rows time creating a schema, which
ArkType's default build does when it builds, so they show little. Speed and
startup hold with any one suite left out; the size lead doesn't ("Size isn't
close" below).

The full board, every suite:

| category | 1             | 2             | 3                   |
| -------- | ------------- | ------------- | ------------------- |
| speed    | ArkType 1.120 | ata 1.254\*   | ajv 2.910\*         |
| startup  | ArkType 1.014 | ajv 1.476\*   | Typia 5.299\*       |
| size     | ajv 1.326\*   | ArkType 1.332 | Superstruct 1.464\* |

\* ranked on 2 to 4 of the category's suites. The homepage's speed suite is
ArkType 1.282, ajv 1.963. ArkType's size: the login form 1002 B (1.072), the
homepage's apps 1.933, schemabenchmarks.dev's download 1879 B (1.198),
Sury's check 270 B (1.268, TypeBox's 213). ajv's: the form 1.000, the
homepage's apps 1.346, schemabenchmarks.dev's download 2718 B (1.733), and
it isn't in Sury's. ArkType's speed average is 10.7% lower than the next
best's and its startup average 31.3% lower; ajv's size average is 0.4% lower
than ArkType's, within the 5% that counts as first.

### The headline's suites

The headline and the homepage's board rank by the independent suites only,
every qualifying suite but the four we designed (the homepage's benchmark,
`startup.ts`, the homepage's cold start and the homepage's apps), so
ArkType's own benchmarks don't decide its claims. It applies to all three
categories alike. valibot.dev's login form counts, and it's partly ours: its
schema is Valibot's code from valibot.dev, but we wrote it in every other
library (`forms/`) and wrote the script that sizes it. The site says so
wherever it states these standings (`isWrittenByUs`). Size's lead doesn't
survive leaving it out. `independentSuites` in
`ark/docs/lib/bench/leaderboard.ts` is the rule, and `claims.ts` computes
the headline, the board and their notes from it, so a rerun that changes a
standing changes the copy. The build throws if the copy names a category's
superlative, or says "Pick 3", while ArkType can't claim it: it needs the
best average, or one within 5% of it.

The rule was chosen on 2026-10-25, after the standings above were known, as
the subset a reader can check fastest: no suite in it is ours. Every other
uniform subset we computed (suites by library count, suites that measure all
three categories, rows without boolean checks, libraries measured on every
suite) left size with ajv or Typia too, and some only by unranking the
runners-up. Wherever the headline's standings are stated, the site states
ArkType's place on the full board beside them.

### Which libraries the site names

Every standing, average and tie counts every library on the rows. The
homepage, its social card and the blog post's numbers name a library only if
its npm package had at least 100k downloads in the week before
(`wellKnownDownloads` in `ark/docs/lib/bench/leaderboard.ts`), so the
libraries named are ones a reader knows. Where the next best or the leader
isn't named, the copy says "the next best" or "the best" and names the best
library that is beside it. The docs build throws if the homepage or the blog
post names one under the cutoff.

`node downloads.ts` asks npm's public API
(`api.npmjs.org/downloads/point/last-week/<package>`) for each library on a
row and writes `results/downloads-<date>.json`, which `leaderboard.ts` copies
into `leaderboard.json`. The week of 2026-10-16 to 2026-10-22:

| library                                 | package                         | downloads   | named |
| --------------------------------------- | ------------------------------- | ----------- | ----- |
| ajv                                     | `ajv`                           | 249,308,485 | yes   |
| Zod, Zod Mini, Zod 3 and Zod (compiled) | `zod`                           | 221,643,257 | yes   |
| TypeBox                                 | `@sinclair/typebox` + `typebox` | 81,996,242  | yes   |
| Effect Schema                           | `effect`                        | 31,551,008  | yes   |
| Joi                                     | `joi`                           | 15,736,800  | yes   |
| Valibot                                 | `valibot`                       | 14,436,274  | yes   |
| Yup                                     | `yup`                           | 7,451,643   | yes   |
| @cfworker/json-schema                   | `@cfworker/json-schema`         | 6,709,707   | yes   |
| Superstruct                             | `superstruct`                   | 4,325,353   | yes   |
| @exodus/schemasafe                      | `@exodus/schemasafe`            | 2,815,227   | yes   |
| io-ts                                   | `io-ts`                         | 1,780,315   | yes   |
| ArkType                                 | `arktype`                       | 1,445,087   | yes   |
| @sapphire/shapeshift                    | `@sapphire/shapeshift`          | 1,000,634   | yes   |
| sury                                    | `sury`                          | 269,129     | yes   |
| Typia                                   | `typia`                         | 211,406     | yes   |
| runtypes                                | `runtypes`                      | 147,816     | yes   |
| pure-parse                              | `pure-parse`                    | 45,285      | no    |
| zod-compiler                            | `zod-compiler`                  | 40,310      | no    |
| @remix-run/data-schema                  | `@remix-run/data-schema`        | 32,295      | no    |
| decoders                                | `decoders`                      | 18,035      | no    |
| rescript-schema                         | `rescript-schema`               | 12,657      | no    |
| ts-auto-guard                           | `ts-auto-guard`                 | 10,319      | no    |
| ata                                     | `ata-validator`                 | 3,913       | no    |
| @sinclair/typemap/valibot               | `@sinclair/typemap`             | 1,971       | no    |
| spectypes                               | `spectypes`                     | 534         | no    |
| ts-runtime-checks                       | `ts-runtime-checks`             | 294         | no    |
| stnl                                    | `stnl`                          | 97          | no    |
| type-predicate-generator                | `type-predicate-generator`      | 87          | no    |
| @sx3/gate                               | `@sx3/gate`                     | 19          | no    |
| @railway-ts/pipelines                   | `@railway-ts/pipelines`         | 14          | no    |
| @ts-runtypes                            | `@ts-runtypes/core`             | 9           | no    |
| paseri                                  | none: it publishes to JSR only  | 0           | no    |

The cutoff sits in the widest gap near the least-downloaded validator
readers know: Typia has 211k, runtypes 148k and pure-parse, the
most-downloaded below them, 45k. Downloads count dependents too, so
@cfworker/json-schema, @exodus/schemasafe and @sapphire/shapeshift clear it
mostly as other packages' dependencies. None of them is named today.

### The rule

**Categories and benchmarks.** Each category is a set of suites, each suite a
set of rows. A row is one measured result per library; lower is better on
every row.

| category | suite                                       | rows                                              | measure                                                               |
| -------- | ------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------- |
| speed    | moltar's typescript-runtime-type-benchmarks | parseSafe, parseStrict, assertLoose, assertStrict | instructions per call (`results/counts-*.json`)                       |
| speed    | the homepage's benchmark                    | its 32 scenarios                                  | median ns per call (`ark/docs/lib/bench/benchData.json`)              |
| startup  | `startup.ts`                                | its scenarios on Node 24                          | median instructions, less the baseline bundle's (`results/startup-*`) |
| startup  | the homepage's cold start                   | its apps                                          | median ms from import to first validation (`benchData.json`)          |
| size     | valibot.dev's login form                    | the form, written in each library (`forms/`)      | gzipped bytes (`results/forms-*.json`)                                |
| size     | the homepage's apps                         | its apps                                          | gzipped bytes (`benchData.json`)                                      |

Which public suites belong in the table is decided by the rule under
"Which suites" below, which adds schemabenchmarks.dev, Sury's schema
benchmark and ata's validator-benchmarks. The wall-clock runs aren't suites:
they time a subset of moltar's rows and libraries that the counts already
cover.

**ArkType's build.** One config everywhere: the default options in a
production esbuild build, which prunes by usage. Where a suite bundles,
every library is bundled the same way. ArkType's other builds (the
"smallest" preset, errors: "first", dynamic, 2.2.9) are left out of every
row, including when finding a row's best. The homepage's size and cold-start
rows were bundled for development, so before averaging they are rebuilt and
remeasured with every library in production (`bench/bundle.ts`); its speed
rows run ArkType's validators as precompiled, which pruning doesn't change.
The login form is remeasured at the same commit.

**Libraries.** Every library in any suite. A library's variants in one suite
(a mode in parentheses after its name, as in moltar's TypeBox and ata
cases, or the form's TypeBox TypeCompiler and Value) count as that library,
by its best variant on each row; Zod, Zod Mini and z.compile stay three, as the homepage names
them.

**Average.** On each row, a library's ratio is its result over the best
result any library has on that row. Its score in a suite is the geometric
mean of its ratios over the suite's rows it's measured on, and its score in
the category is the geometric mean of its suite scores, so each suite weighs
the same however many rows it has. The best score wins the category.

**Ties.** In every category, a score within 5% of the best counts as first,
so ArkType may claim a category with a score up to 1.05 times the best, and
any other library within it counts as first beside it. Where ArkType is first
by the band rather than the best score, the site names the library with the
best average and says ArkType is within 5% of it; where ArkType has the best
score, it says by how much. One release can move a result by about that
much: Valibot 1.5.0's bundle in Sury's suite is 3.3% smaller than 1.4.2's,
and moving from Node 24 to 25 changed `startup.ts`'s counts by 0 to 6% per
library (`results/startup-4fd880692-node24.json` and `-node25.json`). `tieBand` in
`ark/docs/lib/bench/leaderboard.ts` is the band. It was set for size on
2026-10-25, with the standings above known, making Typia's 3.3% lead on size
one ArkType could claim, and applied to speed and startup alike the same day.

**Coverage.** A library's suite score counts only if it's measured on at
least half that suite's rows. It's ranked in a category only if it has a
counted score in at least half of the category's suites.

**Claiming.** The site states that ArkType is first in a category only
where it's first by this rule on the headline's suites and on every suite,
ours included, so that our own benchmarks can't contradict a claim. Startup
needs one more thing, since its independent rows time only creating a
schema: on each of `startup.ts`'s apps, the default build must run fewer
instructions than every library, by median and by a two-sided sign test over
the rounds paired by run (p < 0.05).

**Use.** `ark/repo/bench/external/leaderboard.ts` gathers every row into
`ark/docs/lib/bench/leaderboard.json`; `ark/docs/lib/claims.ts` computes the
scores from it and throws if the headline claims a category ArkType can't
claim. Nothing is rerun to change a result: the weekly rerun runs on its
schedule whatever the last one showed.

### Which suites

A skeptic's first question is why these suites. This rule, written at
2026-10-23T22:12Z before any search for suites and before ArkType's standing
in any suite not above was seen, decides it. A suite counts in a category iff:

1. its harness and its results are public;
2. its harness or its published results changed in the last 12 months;
3. it measures the category on runtime validators: time or instructions per
   validation or parse (speed), to create a schema or import and first
   validate (startup), or bytes of bundles that use a validator (size).
   Type-checking time and memory are other categories;
4. it measures both Zod and Valibot, so it compares the field rather than two
   libraries;
5. it runs locally from its own steps, plus adding a library the way it adds
   one. One that can't is listed with its published results, outside the
   average.

Who runs a suite doesn't matter: a library author's benchmark counts as ours
does. Rows are the suite's own, in its own measure, except that wall-clock
rows are counted in instructions while the machine's 1-minute load is 4 or
more, as moltar's are here. ArkType enters each as the default build, added
the way the suite adds a library; where a suite already has `type()`, that
arm is dynamic ArkType and is left out like ArkType's other builds.

| suite                                          | run by                   | verdict                                                                                                                      |
| ---------------------------------------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| moltar's typescript-runtime-type-benchmarks    | moltar                   | in (speed)                                                                                                                   |
| schemabenchmarks.dev (open-circle)             | Open Circle              | in: speed (26 rows), startup (initialization), size (download)                                                               |
| Sury's schema benchmark (`docs/benchmarks`)    | Sury's author            | in: speed (parse), startup (build and parse once), size (what a check of the schema ships); its whole-library row is out (3) |
| ata's validator-benchmarks                     | ata's author             | in (speed, 12 rows)                                                                                                          |
| the homepage, `startup.ts`, valibot.dev's form | us, and Valibot's author | in                                                                                                                           |
| Zod's published comparisons                    | Zod's author             | out as a suite: its cross-library numbers are moltar runs, its sizes Zod against Zod Mini (4)                                |
| typia's `benchmark/`                           | typia's author           | out: no Valibot (4)                                                                                                          |
| TypeBox's benchmarks                           | TypeBox's author         | out: ajv only (4)                                                                                                            |
| icebob/validator-benchmark and smaller repos   | various                  | out: unchanged since 2024 or before (2)                                                                                      |
| blog comparisons, bundlephobia, pkg-size       | various                  | out: no harness, or the whole package rather than a bundle using it (1, 3)                                                   |

How each new suite is run, at the commits measured (schema-benchmarks
94e2dccc on Node 26.12.1, its `.node-version`; Sury 1f035c5 and ata's
8676ca6 on Node 24.14.1, with their own pinned installs):

- schemabenchmarks.dev: `sb/precompiled/` is added to the clone as
  `schemas/libraries/arktype/precompiled/`, as zod-compiler is added: its
  generate.ts compiles the arktype entry's schema with the suite's tsdown
  config and the precompile plugin (with `node_modules/arktype` linked to
  this repo's `ark/type`), and `sb/download.patch` adds the plugin to the
  download test for that entry, as typia's is. Rolldown and tsdown can't tell
  the plugin a build is for production, so it's given what the default
  resolves to in one: `prune: true` and the production defaults. After
  `vp pack --no-dts` in `schemas`, `sb/allArms.ts` lists every runtime case of
  every library and `count.ts` counts them (`COUNT_ARMS=out/sb-arms.json`);
  the download test is the suite's own script.
- Sury's: `sury/cases.ts` is its schema topic's timed calls verbatim,
  bundled against its installs, and `sury/arktype.ts` the same ArkType calls,
  precompiled (`sury/bundle.ts`, `sury/arms.ts`, then `count.ts`).
  `sury/size.ts` is its bundle-size code with its esbuild, each bundle run on
  its value before it's counted; ArkType's snippet is a file, `sury/schema.ts`,
  since the precompiler doesn't read esbuild's stdin. It also bundles each
  library's boolean check of the same schema, which must reject a value with
  a string for a number too: `S.isInput`, Zod's `safeParse().success`,
  Valibot's `v.is`, the code TypeBox's `TypeCompiler.Code` writes, and
  ArkType's `.allows` (`sury/check.ts`).
- ata's: `ata/validators.ts` writes its user and order bodies in ArkType,
  `ata/build.ts` precompiles them, and `ata/impls.patch` adds an adapter as
  typia's is added. `ata/arms.ts` and `count.ts` count instructions per
  document; a child exits where an adapter disagrees with a scene.

Two startup rows time no build for a library that compiles ahead of time:
schemabenchmarks.dev's initialization and Sury's build-and-parse-once.
ArkType's default build creates a validator once and reuses it (16 and 102
instructions, at the harness's floor beside zod-compiler's 16 and TypeBox's
ahead-of-time 153; typia's createIs 381; "Versions and modes" below), so on
those rows it wins by what the rows don't measure. They're the suites' rows,
so they stay.

### Versions and modes

Each suite pins its own installs, and some pins trail what a reader would
install today: moltar's typia 9.7.2 and ata-validator 1.32.1, ata's suite's
own ata-validator 1.48.0, Sury's zod 4.4.3 and valibot 1.4.2. So each suite's
rivals are counted twice, at its pins and at the latest npm releases of
2026-10-24 (`--latest`, `results/*-latest-2026-10-24.json`), and each arm
keeps its faster count. Rivals can only gain from this. The weekly rerun of
the size suites adds a third install, each rival at its newest release
(`results/newest/`). Newer isn't always faster: ata 1.60.0 takes 195
instructions on moltar's assertLoose to 1.32.1's 94, so moltar's ata rows
keep 1.32.1.

| suite                | at their latest releases                                                                                                        | left at the suite's pin                                                                             |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| moltar's             | typia 15.2.1, ata-validator 1.60.0, @ts-runtypes 0.12.2, @sx3/gate 1.0.10, pure-parse 1.0.3, zod 4.6.7, valibot 1.5.0           | stnl 1.1.6 and sury 11.0.0-rc.2, whose latest releases break moltar's cases for them                |
| schemabenchmarks.dev | its 1c842272, with ata-validator 1.60.0 and typia 15.2.1                                                                        | none: the rest are current                                                                          |
| Sury's               | zod 4.6.7, valibot 1.5.0                                                                                                        | @sinclair/typebox 0.34.52, that package's latest (TypeBox 1 is a new package the suite doesn't use) |
| ata's                | ata-validator 1.60.0, typia 15.2.1, zod 4.6.7                                                                                   | @sinclair/typebox 0.34.52, as in Sury's                                                             |
| ours                 | every library at its latest but typia 15.1.0, whose 15.2.1 writes the same validators byte for byte, and TypeBox 1.3.37 (1.4.3) | not counted again: TypeBox is last but one on the homepage's speed suite                            |

Each library is measured on its suite's own operation (what the suite calls
for that library: a parse, an assert, a check) in its fastest or smallest
documented mode. A mode counts when it does that operation, and changing one
library's operation doesn't: only a change to the suite's, for every
library. So each rival runs in its fastest documented mode wherever the
suite allows it: typia's compiled `createIs`, `createValidate` and `createAssert`,
TypeBox's compiler, ajv's compiled validators (its standalone code where a
suite measures size), ata's ahead-of-time modules, paseri's, Sury's compiled
parsers and Zod's `z.compile`, counted as Zod (compiled). Where a suite had
no arm for a mode, it's added as ArkType's arm is: `z.compile` in Sury's and
ata's suites, Valibot's `v.is` for ata's verdicts, and ata's modules for
schemabenchmarks.dev's string formats (`sb/ataCompiled.ts`, `sb/ata.patch`).
ata won't write that suite's product schema as a module: its Date check is a
`withKeywords()` wrapper JSON Schema can't express. ata's config body needs a
5 s warmup to count reproducibly (`COUNT_WARM_US`); after 1 s, one arm's
reps spread up to 2.3x.

schemabenchmarks.dev's download sized ajv as its runtime, compiling the
product schema where it runs (41477 B gzipped), against ArkType's
precompiled build. `sb/ajvStandalone.ts` adds ajv's standalone code for the
same schema and options, run through the suite's own download script
(Rolldown, minified, gzipped) with the runtime helpers it imports: 20300 B,
2718 B gzipped. ajv keeps the smaller, which moved size from ArkType 1.355
against Valibot's 1.394 to ajv 1.326 against ArkType's 1.355. The other
download rows are byte for byte the committed run's.

Sury's size row measures a boolean check, for every library. The suite
bundles a different operation per library (Sury's `parseOrThrow`, Zod's and
Valibot's parse, ArkType's `.assert`, TypeBox's `Check`), so its row
compared a throwing parse against TypeBox's check. Each library is now
sized on its documented boolean check of the same schema, the operation the
suite gives TypeBox, alongside the suite's own snippet, and keeps the
smaller: Sury's `S.isInput` (11616 B, its parse 11599), Zod's
`safeParse().success` (64689, its parse 64686), Valibot's `v.is` (1198, its
parse 1261), TypeBox's ahead-of-time Check, the code `TypeCompiler.Code`
writes, with no imports (213, its compiler 22568), and ArkType's `.allows`
(289, its `.assert` 1107). The change is to the suite's operation, for every
library, so it counts under the rule above. TypeBox leads the row; ArkType
was second at 1.357. The rivals' bundles of the suite's own snippets are
byte for byte the earlier runs'. ArkType's check was measured at 396778442,
beside 808927feb's `.assert`; both are now 2c1a6a86e's, the check 270 B
(1.268) and `.assert` 1014 B. The other size suites' TypeBox
operations report errors, which the ahead-of-time Check doesn't. In TypeBox
1, `typebox/compile`'s `Code` is the same Check.

The same gap was in the two independent startup rows. schemabenchmarks.dev
times initialization only for libraries that build a schema at runtime: its
own precompiled entries, zod-compiler and @paseri/compiler, have no such
case. `sb/aotInit.ts` gives ajv's standalone code, zod-compiler and
@paseri/compiler one that returns the schema their module made as it loaded,
and ArkType's precompiled arm reads its schema the same way
(`sb/precompiled/benchmarks.ts`, 11067f517), where it had called a getter.
Sury's build and parse once runs TypeBox's ahead-of-time Check beside its
`Value.Check`. In instructions per call, one run of every ahead-of-time arm
(`results/sb-counts-init-11067f517.json`, Node 26.12.1, 3 reps):
zod-compiler 15.943, ArkType 15.954, @paseri/compiler 15.957, ajv 19.971,
typia's createIs 381.2, the first three at the harness's floor, each arm's
reps spreading 0.4-0.7%. On Sury's build, ArkType 101.9
(`results/arktype-init-11067f517.json`, the build at 91d3e2e20) and TypeBox
153.0 (`results/sury-counts-aot-2026-10-25.json`). Over the independent
suites, startup is then zod-compiler 1.000 (one suite), ArkType 1.000 and
@paseri/compiler 1.001 (one suite): ArkType counts as first within 5% of
zod-compiler. On the full board ArkType led, 1.013 to ajv's 1.449.

With ArkType's rows unchanged, the update moved speed from ArkType 1.103
against ata 1.255 to 1.107 against 1.255, left startup alone, and moved size
from 1.355 against Valibot's 1.405 to 1.355 against 1.394: Valibot 1.5.0's
bundle in Sury's suite is 1261 B gzipped, 1.4.2's 1304.

### Objections

**"Half of these benchmarks are yours."** We designed 1 of the 5 speed suites,
2 of the 4 startup suites and 1 of the 4 size suites, and the headline counts
none of them ("The headline's suites"). It does count valibot.dev's login
form, a size suite: its schema is Valibot's, but we wrote it in every other
library and wrote the script that sizes it. Without it, size goes to
@railway-ts/pipelines (one suite), then Typia 1.177, @remix-run/data-schema
1.226 and ArkType 1.232. On the full board, with ours, speed is ArkType
1.120 against ata 1.254 (the homepage's suite is ArkType's worst, 1.282),
startup ArkType 1.014 against ajv 1.476, and size ajv 1.326 against
ArkType's 1.332. Startup without ours is two rows that time creating
a schema, which a precompiled build doesn't do, so they show little; with
ours, which time whole apps from import to first validation, ArkType is
still first. ata, the closest at speed, isn't in the homepage's suite or
Sury's; its average is over the three suites it's in.

**"Instruction counts aren't time."** They aren't. They're the measure
because these runs share a machine (1-minute loads of 9 to 20), and wall
clock there measures the neighbors. A count misses cache misses and branch
mispredictions, so it favors code that does less work badly. Where both
were measured, they mostly rank alike: by wall clock, in paired runs, the default
build beat each of the six libraries closest to it on moltar's parseSafe in
28 or 29 of 30 passes (p 8.7e-7) and ts-runtime-checks on assertLoose in 24
of 30 (p 0.0014), as their counts order them ("The release's wall-clock
run"). Not always: in the same plan's run at the release candidate,
the default build took the fewest instructions on parseSafe, but
rescript-schema and @sx3/gate were faster by wall clock in 21 and 24 of 30
passes, so H1 failed there ("The release candidate's run"). The homepage's
suite is wall clock: median ns over 20 passes and a
10-pass replica.

**"Best average is cherry-picked."** The rule (which suites count, a ratio
to each row's best, a geometric mean per suite, each suite weighted the
same) was written at 2026-10-23T22:12Z, before any search for suites. Its
first averages had ArkType losing speed and size, and they stay below as
records. Speed and startup hold with any one suite left out. Speed's
closest is without schemabenchmarks.dev: ArkType 1.074, 6.7% lower than
ata's 1.151.

**"Size isn't close."** Over the independent suites ArkType leads it,
1.176, 6.3% lower than Typia's 1.256 on the two of three Typia is in, but the lead
doesn't survive leaving out any one suite: without the form, Typia 1.177
and @remix-run/data-schema 1.226 come before ArkType's 1.232; without
schemabenchmarks.dev's download, ajv 1.000 (one suite) before ArkType's
1.166; without Sury's, @railway-ts/pipelines 1.000 (one suite) before
ArkType's 1.133. At 624a5d716's size rows ArkType led, 1.240 to 1.256,
and at 808927feb's Typia led, 1.256 to 1.297. On the full board ajv leads
it, 1.326, 0.4% lower than ArkType's 1.332, so both count as first. ajv's lead survives leaving out schemabenchmarks.dev's download (ajv
1.160 in two of three suites, ArkType 1.380) or Sury's (ajv 1.326, ArkType
1.354), not the form (ArkType 1.432, ajv 1.527) or the homepage's apps
(ArkType 1.176, Typia 1.256). Valibot ships less than the default build on
2 of the 7 size rows, the homepage's shop and saas, and ajv's standalone
code has the best score on the form and on the homepage's apps.

**"Precompiled against runtime is apples to oranges."** Every library that
documents a compiled mode is measured in it, where the suite's schema
compiles ("Versions and modes"): typia, ata, TypeBox, ajv, Sury, paseri,
@ts-runtypes and `z.compile`, and TypeBox's ahead-of-time Check in Sury's
bundle and build, and ajv's standalone code, zod-compiler and
@paseri/compiler in schemabenchmarks.dev's initialization. Valibot, Zod Mini and the rest run as
they ship, since they have no other mode. Plain `type()`, ArkType with no
build step, is left out of every row, and so is every build but the
default. The build step is a cost these numbers don't show: ArkType's
default build needs its bundler plugin.

### History

Each average below was computed at the commit it names, before the current
standings, and stands as its record. Nothing in it was rerun to change a
result.

#### ArkType's rows at 808927feb, rivals at their latest releases

The current standings' suites, before ArkType's rows were measured again at
781130da3 and its size rows at 2c1a6a86e.

ArkType's rows were measured at 808927feb, after the first issue began to be
pushed directly (a size trade) and object issues began to be reported in
declaration order: `benchData.json`'s scenarios rerun, 20 passes then a
10-pass replica, every library in, at 1-minute loads of 2.3 to 4.9 at the
runs' starts and ends (each started under 4); every other ArkType row in
`results/arktype-808927feb.json` and `results/startup-808927feb-node24.json`.

Each rival arm is the faster of two counts, at its suite's pins and at the
latest releases ("Versions and modes" above).

The headline's standings, over the 9 independent suites: 4 for speed (43
rows), 2 for startup (2) and 3 for size (3).

| category | 1             | 2             | 3                             |
| -------- | ------------- | ------------- | ----------------------------- |
| speed    | ArkType 1.067 | ata 1.255\*   | paseri 2.142\*                |
| startup  | ArkType 1.000 | Typia 8.962\* | @railway-ts/pipelines 186.8\* |
| size     | Typia 1.256\* | ArkType 1.297 | ajv 1.317\*                   |

\* ranked on half to three quarters of the category's suites. Leads: speed
17.6%, startup 796%; Typia leads size by 3.3%, on the form and
schemabenchmarks.dev's download (it isn't in Sury's), within the 5% that
counts as first. Both startup rows time creating a schema, which ArkType's
default build does when it builds, so they show little. Speed and startup hold with any one suite left out.

The size rows were then rerun (`results/newest/`, "Weekly" under
"Reproduce"): ArkType at 624a5d716, its form 1107 B, schemabenchmarks.dev's
download 1934 B and Sury's check 278 B, every rival at its newest release of
2026-10-25. The headline's size standings were then ArkType 1.240, Typia
1.256\*, ajv 1.317\*, and the full board's ajv 1.326\*, ArkType 1.414,
Superstruct 1.464\*. The run before it, at 2cc2aa949 (form 1116 B, download
1977 B, the same rivals), had ArkType 1.252. The tables are the record at 808927feb.

The full board, every suite:

| category | 1             | 2             | 3                   |
| -------- | ------------- | ------------- | ------------------- |
| speed    | ArkType 1.107 | ata 1.255\*   | ajv 2.912\*         |
| startup  | ArkType 1.013 | Typia 2.815\* | Valibot 18.0        |
| size     | ajv 1.326\*   | ArkType 1.462 | Superstruct 1.464\* |

\* ranked on 2 to 4 of the category's suites. The homepage's speed suite is
ArkType 1.282, ajv 1.963. ArkType's size: the login form 1158 B, the
homepage's apps 2.095, schemabenchmarks.dev's download 2037 B (1.299),
Sury's check 289 B (1.357, TypeBox's 213). ajv's: the form 1.000, the
homepage's apps 1.346, schemabenchmarks.dev's download 2718 B (1.733), and
it isn't in Sury's. Leads: speed 13.4%, startup 178%; ajv leads size by
10.3%.

At 808927feb's rows ajv's size lead survived leaving out
schemabenchmarks.dev (ajv 1.160, in two of three suites), Sury's (ajv 1.326,
with ArkType fourth at 1.499) or the form (ajv 1.527 to ArkType's 1.546),
not the homepage's apps (Typia 1.256 in two of three, ArkType 1.297).
Valibot shipped less than the default build on 3 of the 7 size rows.
Without the form, size went to @railway-ts/pipelines (one suite), then
Typia 1.177, then ArkType 1.283. Speed's closest without one suite was
without schemabenchmarks.dev: ArkType 1.110, ata 1.151, a 3.7% lead.

#### Sury's size row as the suite's operations

The standings before Sury's size row compared each library's boolean check,
when it bundled the suite's own snippets (ArkType's `.assert`, 1107 B, best
on the row) and TypeBox's compiler. Everything else is the standings'
above, at 808927feb.

| category | 1             | 2             | 3             |
| -------- | ------------- | ------------- | ------------- |
| speed    | ArkType 1.107 | ata 1.255\*   | ajv 2.912\*   |
| startup  | ArkType 1.013 | Typia 2.815\* | Valibot 18.0  |
| size     | ajv 1.326\*   | ArkType 1.355 | Valibot 1.394 |

\* ranked on 2 to 4 of the category's suites. Leads: speed 13.4%, startup
178%; ajv leads size by 2.2%.

#### ajv's runtime in schemabenchmarks.dev's download

The standings before ajv's standalone code was sized there. Everything else
is the standings' above, at 808927feb.

| category | 1             | 2             | 3                   |
| -------- | ------------- | ------------- | ------------------- |
| speed    | ArkType 1.107 | ata 1.255\*   | ajv 2.912\*         |
| startup  | ArkType 1.013 | Typia 2.815\* | Valibot 18.0        |
| size     | ArkType 1.355 | Valibot 1.394 | Superstruct 1.464\* |

\* ranked on 2 to 4 of the category's suites. Leads: speed 13.4%, startup
178%, size 2.9%.

#### ArkType's rows at 808927feb, rivals at the suites' pins

The standings before rivals were counted at their latest releases. The
suites, rows and ArkType's rows are those above, at 808927feb.

| category | 1             | 2             | 3                   |
| -------- | ------------- | ------------- | ------------------- |
| speed    | ArkType 1.103 | ata 1.255\*   | ajv 2.873\*         |
| startup  | ArkType 1.013 | Typia 2.815\* | Valibot 29.4        |
| size     | ArkType 1.355 | Valibot 1.405 | Superstruct 1.464\* |

\* ranked on 2 to 4 of the category's suites. Leads: speed 13.8%, startup
178%, size 3.7%.

#### The first average, at 642b4517e

`ark/docs/lib/bench/leaderboard.json`; the score is the geometric mean of
ratios to each row's best, so 1 is best everywhere.

| category | 1                    | 2             | 3                   | 4              | 5                         |
| -------- | -------------------- | ------------- | ------------------- | -------------- | ------------------------- |
| speed    | @ts-runtypes 1.101\* | ata 1.141\*   | ArkType 1.211       | paseri 1.302\* | ts-runtime-checks 1.330\* |
| startup  | ArkType 1.083        | Valibot 1.256 | ajv 1.385           | Typia 1.402    | Zod Mini 3.395            |
| size     | ajv 1.160            | Valibot 1.588 | Superstruct 1.736\* | Typia 1.812    | ArkType 2.069             |

\* ranked on one of the category's two suites. ArkType has the best score in
each speed suite on its own (moltar's 1.067, the homepage's 1.375), but
@ts-runtypes and ata are only in moltar's, so the rule averages ArkType's
homepage score in and not theirs. So only startup backs a superlative.

One deviation: the homepage's cold-start rows weren't remeasured in
production. The 1-minute load stayed above 15 for 40 minutes; a run at 16-22
put every arm at 4x its quiet time and tied all of them. The quiet,
development-built rows stand, which only handicap ArkType (its build there
isn't pruned). With the loaded production rows instead, startup's order is the
same: ArkType 1.098, Valibot 1.289.

#### Every qualifying suite, at 6c5fd9862

lane/homepage with lane/integrate 3381cbce3. Each suite's rivals were counted
at 4971a30a1 and ArkType's arms again at 6c5fd9862 (no rival depends on the
build). `results/sb-counts-*`, `sb-download-*`, `sury-counts-*`,
`sury-size-*` and `ata-counts-*`; `node standings.ts [suites]` prints the
standings over any set of suites.

| category | 1             | 2                   | 3             | 4             |
| -------- | ------------- | ------------------- | ------------- | ------------- |
| speed    | ata 1.151\*   | ArkType 1.186       | ajv 2.645\*   | Typia 3.449\* |
| startup  | ArkType 1.041 | Typia 2.602\*       | Valibot 27.3  | Zod Mini 59.7 |
| size     | Valibot 1.349 | Superstruct 1.464\* | Typia 1.570\* | ArkType 1.699 |

\* ranked on 2 to 4 of the category's suites. Each suite's own scores:
ArkType has the best score in every speed suite but schemabenchmarks.dev
(1.468, ata 1.154), and the best in every startup suite but the homepage's
cold start (1.054, Valibot 1.050). In size it's best in none: the login form
1.705 (ajv 1.000), the homepage's apps 2.511 (ajv), schemabenchmarks.dev's
download 1.657 (2598 B against @railway-ts/pipelines' 1568, Typia 1846,
Valibot 2058), Sury's 1.174 (1531 B against Valibot's 1304).

Speed turns on schemabenchmarks.dev's string formats and invalid Standard
Schema row, where ata's checks take a fraction of ArkType's instructions:
uuid 27 against 227 invalid (8.3x) and 495 against 1137 valid, date-time 95
against 268 invalid, ipv6 266 against 709 invalid, and Standard Schema's
invalid row 57308 against Sury's 31528 (1.8x). ata isn't in the homepage's
suite, where ArkType's score is 1.375. Leaving out one suite at a time,
ArkType leads speed without the homepage's (1.143, ata 1.151) or without
schemabenchmarks.dev (1.125), and ata leads otherwise.

#### ArkType's rows at 90d510484

Every ArkType row was measured again on one commit, 90d510484, the default
build in every suite: `results/arktype-90d510484.json` holds them in each
suite's own format, and `leaderboard.ts` puts them over each suite's
rivals, which don't depend on ArkType's build. `startup.ts` was run whole
there (`results/startup-90d510484-node24.json`), rivals included. The
homepage's apps are sized as production builds (`bench/bundle.ts`, above).

The homepage's speed rows are now instructions per call (`count.ts`), as
"Which suites" counts wall-clock rows measured at a 1-minute load of 4 or
more, which it was. Its rivals are the counts at 54777c69a
(`results/homepage-counts-54777c69a.json`): ajv, Valibot and z.compile.
Zod, Zod Mini, Typia and TypeBox aren't counted there, so their speed scores
average one suite fewer. None of them is fastest on any of the suite's rows
by wall clock, so ArkType's score doesn't depend on them. With the suite in
`benchData.json`'s median ns, every library in, ArkType still leads speed
(1.116 against ata's 1.253 with 7daf33b7e's rows). The homepage's cold
start is still its quiet, development-built ms.

| category | 1             | 2             | 3                   | 4             |
| -------- | ------------- | ------------- | ------------------- | ------------- |
| speed    | ArkType 1.096 | ata 1.251\*   | Typia 2.767\*       | ajv 2.876\*   |
| startup  | ArkType 1.013 | Typia 2.791\* | Valibot 29.2        | Zod Mini 64.7 |
| size     | ArkType 1.372 | Valibot 1.400 | Superstruct 1.464\* | Typia 1.570\* |

\* ranked on 2 to 4 of the category's suites. ArkType has the best score in
every speed suite: moltar's 1.067, the homepage's 1.251, schemabenchmarks.dev's
1.078 (ata 1.485), Sury's 1.000 and ata's 1.097 (ata 1.156). It has the best
in every startup suite but the homepage's cold start (1.054, Valibot 1.050),
and the fewest instructions on all four of `startup.ts`'s apps. In size it's
best in Sury's (1124 B, Valibot 1304) and second to ajv on the login form
(1172 B; ajv 935, Typia 1252); the homepage's apps 2.118 (ajv 1.346, Valibot
1.508) and schemabenchmarks.dev's download 1.336 (2095 B against
@railway-ts/pipelines' 1568, Valibot 2058). Its size lead is 2.0%.

At 7daf33b7e, the commit before, size was Valibot 1.360 against ArkType
1.462, with speed 1.092 and startup 1.014 leading.

#### ArkType's rows at fea8e68e0, the homepage's speed in ns

The homepage's speed suite is scored by the table's measure again, median
ns per call from `benchData.json`, every library from one run. Counting it
in instructions under load (above) changed the registered row, so that
section's homepage scores stand only as its record;
`results/homepage-counts-*.json` are kept with it. `benchData.json`'s
scenarios were rerun at fea8e68e0 on a quiet machine: 20 passes, then a
10-pass replica, by its provenance's procedure, at 1-minute loads of 2.1 to
3.4 at the runs' starts and ends. Its sizes and cold start aren't rerun.
Every other ArkType row was measured again at the same commit
(`results/arktype-fea8e68e0.json`, `results/startup-fea8e68e0-node24.json`).

| category | 1             | 2             | 3                   | 4             |
| -------- | ------------- | ------------- | ------------------- | ------------- |
| speed    | ArkType 1.105 | ata 1.249\*   | ajv 2.866\*         | Typia 3.675\* |
| startup  | ArkType 1.013 | Typia 2.815\* | Valibot 29.4        | Zod Mini 65.2 |
| size     | ArkType 1.363 | Valibot 1.404 | Superstruct 1.464\* | Typia 1.570\* |

\* ranked on 2 to 4 of the category's suites. ArkType has the best score in
every speed suite: moltar's 1.067, the homepage's 1.298 (ajv 1.972),
schemabenchmarks.dev's 1.078 (ata 1.480), Sury's 1.000 and ata's 1.104 (ata
1.155). Startup is as at 90d510484, Valibot best only on the homepage's cold
start. In size it's best in Sury's (1112 B, Valibot 1304) and second to ajv
on the login form (1168 B); the homepage's apps 2.100 (ajv 1.346, Valibot
1.508) and schemabenchmarks.dev's download 1.315 (2062 B). Leads: speed
13.0%, startup 178%, size 3.0%.

## The login form across validators

`forms/` writes valibot.dev's login form in each TypeScript-schema validator
with real usage, as its docs write it, each exporting a validate that reports
every error with the form's messages where the library can attach them
(typia can't, so it keeps its own). `forms/size.ts` bundles each with
login/size.ts's esbuild settings, gzips at level 9, then runs every bundle on
the same four inputs and records what it reports. ajv's row is its standalone
code with ajv-errors: generated from JSON Schema, not a TypeScript schema.

At 54eb5e89b (`results/forms-54eb5e89b.json`, behavior in
`results/forms-behavior-54eb5e89b.json`), gzipped: ArkType precompiled with
the "smallest" preset 1119, ajv standalone 935, typia 1252, ArkType default
1552, Valibot 1564, Superstruct 1623, runtypes 5051, Zod Mini 5124, Yup 13519,
TypeBox 22788 (TypeCompiler) and 25697 (Value), Zod 25076, Joi 54732, dynamic
ArkType 82262, Effect Schema 83215. On a blank password ArkType reports only
the 8-character message: `string > 0` is implied by `string >= 8`, so its
message never fires.

---

### Ark Docs Content Docs Attest Index (`ark/docs/content/docs/attest/index.mdx`)

---
title: Getting started
description: Install attest and run its setup and teardown around your tests.
---

Attest is a testing library that makes your TypeScript types available at runtime. A test can assert on a value's type, the type errors and completions of an expression, and the type instantiations a block costs, next to ordinary value assertions. Assertions work from Vitest, Mocha, Jest or any runner with global setup and teardown hooks.

Benches run as plain scripts. They report how many type instantiations a block contributes, which is deterministic for a given TypeScript version, and how long a call takes.

ArkType uses attest to check that its runtime parser and its types agree, and to keep its editor performance from regressing.

## Installation

<InstallationTabs pkg="@ark/attest" dev />

<Callout type="info">
	attest is still in alpha, so its API can change between minor versions. Your
	feedback will help us iterate toward a stable 1.0.
</Callout>

If you're upgrading, [Upgrading](/docs/upgrading#attest) lists the changes to benches.

## Global setup

Type assertions need `setup` to run once before your tests and `teardown` once after them.

`setup` type-checks your project once and writes what each `attest` call needs, like its argument's type and the type errors in it, to `.attest/assertions.json`. Assertions read that file rather than starting TypeScript in every test worker. `teardown` (also exported as `cleanup`) writes the snapshots your tests populated or updated back into your source files when the run exits.

Add `.attest` to your `.gitignore`.

### Vitest

```ts title="vitest.config.ts"
// @noErrors
import { defineConfig } from "vitest/config"

export default defineConfig({
	test: {
		globalSetup: ["setupVitest.ts"]
	}
})
```

```ts title="setupVitest.ts"
import { setup } from "@ark/attest"

// setup returns teardown, which Vitest calls after the last test
export default () => setup({})
```

Vitest rejects command-line flags it doesn't know, so pass attest [options](/docs/attest/options) to it as `ATTEST_` environment variables. Its own `-u` flag works, and updates attest's snapshots along with Vitest's.

### Mocha

```json title="package.json"
"mocha": {
	"require": "./setupMocha.ts"
}
```

```ts title="setupMocha.ts"
import { setup, teardown } from "@ark/attest"

export const mochaGlobalSetup = () => setup({})

export const mochaGlobalTeardown = teardown
```

### Jest

```js title="jest.config.js"
export default {
	globalSetup: "./setupJest.ts",
	globalTeardown: "./teardownJest.ts"
}
```

```ts title="setupJest.ts"
import { setup } from "@ark/attest"

export default () => setup({})
```

```ts title="teardownJest.ts"
import { teardown } from "@ark/attest"

export default teardown
```

`@ark/attest` is an ES module, so Jest has to run with ES module support, e.g. ts-jest with `useESM` and `NODE_OPTIONS=--experimental-vm-modules`.

### Bun

```ts title="setupBun.ts"
import { setup } from "@ark/attest"

setup({})
```

```bash
bun test --preload ./setupBun.ts
```

You can also list the file under `preload` in the `[test]` section of `bunfig.toml`.

Under `bun test`, assertions compare against existing snapshots, but new or updated snapshots aren't written: attest writes them when the process exits, and `bun test` doesn't emit Node's `exit` event.

## Iterating quickly

Type-checking the project is the slow part of `setup`. Two options cut it down:

- [`skipTypes`](/docs/attest/options#skiptypes) skips the check along with every type assertion, for when you're only changing runtime code.
- [`onlyNamedTestFiles`](/docs/attest/options#onlynamedtestfiles) checks only the test files you name on the command line.

## TypeScript versions

Attest analyzes your project with whichever `typescript` it resolves, which is normally your own install since it's a peer dependency. To test several versions, run your suite once per version, e.g. in a CI matrix that installs each one.

TypeScript 7.1+ is supported through its native API. 7.0.x throws an error asking you to upgrade. Under TypeScript 7:

- Instantiation counts come from running `tsc --extendedDiagnostics --singleThreaded` per bench. `tsc` fully checks a bench's dependencies before measuring it, so work the bench shares with them isn't counted, and counts can run lower than on TypeScript 5 or 6. Re-record bench baselines when you switch.
- Type strings, union ordering and error elaboration can differ, so some snapshots need updating when you switch.
- Benches write temporary `.attest-*` copies beside their source files while measuring, so the source directory has to be writable.

---

### Ark Docs Content Docs Blog Index (`ark/docs/content/docs/blog/index.mdx`)

---
title: Posts
description: Release announcements and deep dives
---

<LinkCard
	title="Announcing ArkType 3.0"
	description="Fast, small and quick to start: pick 3. The build step is your agent's job."
	href="/docs/blog/3.0"
	date="October 26, 2026"
/>

<LinkCard
	title="Announcing ArkType 2.2"
	description="Type-safe regex, validated functions, and native Standard Schema definitions"
	href="/docs/blog/2.2"
	date="March 4, 2026"
/>

<LinkCard
	title="Introducing ArkRegex"
	description="A drop-in replacement for new RegExp() with types"
	href="/docs/blog/arkregex"
	date="October 28, 2025"
/>

<LinkCard
	title="Announcing ArkType 2.1"
	description="Optimized pattern matching from type syntax"
	href="/docs/blog/2.1"
	date="February 27, 2025"
/>

<LinkCard
	title="Announcing ArkType 2.0"
	description="100x faster validation with DX that will blow your mind"
	href="/docs/blog/2.0"
	date="January 17, 2025"
/>

---

### Ark Docs Content Docs Internals Index (`ark/docs/content/docs/internals/index.mdx`)

---
title: Architecture
description: How ArkType is split into @ark/util, @ark/schema, arksets and arktype, and what each package owns.
---

<Callout type="warn" title="Not semver-stable">

`@ark/schema` and `arksets/internal` change whenever `arktype` needs them to, so anything on these pages can break in a minor or patch release. That includes `.internal`, `select` and the schema format. If you import either directly, install the exact versions your `arktype` depends on. `arksets`' own functions are documented in [ArkSets](/docs/sets).

</Callout>

ArkType is four packages, each built on the one before it:

| package       | owns                                                                                                                             | depends on                 |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| `@ark/util`   | Utilities every package shares, like `ParseError`, `Json` and the registry that lets compiled validators reference functions     |                            |
| `@ark/schema` | Nodes: the schema format, node kinds, scopes, validation and the compiler behind it, `ArkErrors`, config and locales             | `@ark/util`                |
| `arksets`     | Set algebra over nodes: intersecting them, reducing them as they're created, discriminating unions and generating JSON Schema    | `@ark/schema`              |
| `arktype`     | The definition syntax (`"string > 5"`, object literals, tuple expressions), its type inference, `type`, `scope` and the keywords | all three, plus `arkregex` |

When you call `type("string > 5")`, `arktype` parses the string into an `@ark/schema` node, `arksets` reduces it as it's created, and the node compiles itself into a validator. The Type you get back is that node:

```ts
const T = type("string > 5")

T.json // { domain: "string", minLength: 6 }
T.internal.kind // "intersection"
```

`arktype` imports `arksets` itself, so you never install or import `@ark/schema` or `arksets` to use ArkType. They're documented here for three cases:

- **Inspecting a Type.** Read its node kinds, its `.json` and its references with [`select`](/docs/internals/nodes#select).
- **Building a Type from data instead of syntax**, such as a converter from another schema format. Pass a schema to [`type.schema` or `rootSchema`](/docs/internals/schemas).
- **Using `@ark/schema` without `arktype`.** Import `arksets` yourself, or see [what works without it](/docs/internals/sets).

---

### Ark Docs Content Docs Json Schema Index (`ark/docs/content/docs/json-schema/index.mdx`)

---
title: Overview
description: Generate JSON Schema from a Type with arktype, or build a Type from JSON Schema with @ark/json-schema.
---

ArkType converts in both directions, with one package for each.

| direction          | package            | API                                             |
| ------------------ | ------------------ | ----------------------------------------------- |
| Type → JSON Schema | `arktype`          | `T.toJsonSchema()`, `T["~standard"].jsonSchema` |
| JSON Schema → Type | `@ark/json-schema` | `jsonSchemaToType(schema)`                      |

## Type to JSON Schema

Every Type has a `toJsonSchema()` method. Nothing else to install:

```ts
const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

const schema = User.toJsonSchema()
```

```json
{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"type": "object",
	"properties": {
		"name": { "type": "string" },
		"age": { "type": "integer", "minimum": 0 }
	},
	"required": ["name"]
}
```

Some things a Type can check, like a `Date`, a `bigint` or a custom `narrow`, have no JSON Schema equivalent. `toJsonSchema()` throws on those unless you tell it what to write instead. See [To JSON Schema](/docs/json-schema/to-json-schema).

Libraries that accept any [Standard JSON Schema](https://standardschema.dev/json-schema) read it from `T["~standard"].jsonSchema`, which never throws for those parts. See [Standard JSON Schema](/docs/json-schema/to-json-schema#standard-json-schema).

## JSON Schema to Type

`@ark/json-schema` parses a JSON Schema into a Type:

<InstallationTabs pkg="@ark/json-schema" />

```ts
import { jsonSchemaToType } from "@ark/json-schema"

const User = jsonSchemaToType({
	type: "object",
	properties: {
		name: { type: "string" },
		age: { type: "integer", minimum: 0 }
	},
	required: ["name"]
})

User.expression // "{ name: string, age?: number % 1 >= 0 }"
// ArkErrors: age must be an integer
User({ name: "Ada", age: 1.5 })
```

A schema written in the call infers its type, so `User` is a `Type<{ name: string; age?: number }>`. See [From JSON Schema](/docs/json-schema/from-json-schema#inferring-its-type) to type a schema declared elsewhere, and [Keyword support](/docs/json-schema/support) for which keywords it understands.

---

### Ark Docs Content Docs Precompile Index (`ark/docs/content/docs/precompile/index.mdx`)

---
title: Overview
description: Compile your Types when you build, and ship only the checks they need.
---

ArkType runs in two modes. Both take the same definitions and infer the same types.

- **Dynamic**: `type()` parses each definition at runtime and compiles it the first time your program uses it. No build step.
- **Precompiled**: [`@ark/aot`](https://github.com/arktypeio/arktype/tree/main/ark/aot) constructs your Types when you build. Each becomes a standalone validator that imports only `arktype/runtime`, so arktype's parser never ships and no code is generated at runtime.

```ts title="vite.config.ts"
import { precompile } from "@ark/aot/unplugin"

export default {
	plugins: [precompile.vite()]
}
```

[Setup](/docs/precompile/setup) covers every bundler, test runner and Next.

Precompiled validators have always been faster and smaller. What they cost was a build step: setup, new errors and a second model of what runs where. If an agent runs your local dev, that's one more loop it's already good at, and every error names its fix, so you get the speed and size [without the cost](#with-agents).

## Speed and size

A validator that compiles at runtime ships its compiler, and one that interprets ships its interpreter. A precompiled build ships neither: only the checks your Types need, and the runtime that reports their errors. <Claim id="buildChoice" /> The [options](/docs/precompile/options) decide which: [`optimize: "size"`](/docs/precompile/options#optimize-and-optimizeerrors) and dropping [`members`](/docs/precompile/options#members) make a build smaller and its validators slower.

<ClaimCharts />

A precompiled validator has no initialization cost, and since nothing is generated at runtime, it runs under a Content-Security-Policy that blocks `eval`.

## Optimized by set theory

ArkType reduces every Type to a normalized set of constraints, so it knows which Types are subtypes of others, which overlap and which can't both be satisfied. Precompiling applies that knowledge in your build:

- **Unions discriminate themselves.** ArkType finds the key that tells a union's branches apart and switches on it, so data is checked against one branch rather than each in turn.
- **Redundant checks disappear.** `number > 0` intersected with `number >= 10` is `number >= 10`, one check, and a branch never rechecks the key it was chosen by.
- **Contradictions never ship.** A definition that intersects to nothing, like `{ id: string }` and `{ id: number }`, throws a ParseError, which fails the build rather than shipping a validator that rejects everything.

```ts
const Shape = type({
	kind: "'circle'",
	radius: "number > 0"
}).or({
	kind: "'square'",
	side: "number > 0"
})
```

Precompiled, `Shape` checks data like this, its helpers inlined:

```ts
// @noErrors
// ---cut---
data => {
	switch (data?.kind) {
		case "circle":
			return Number.isFinite(data.radius) && data.radius > 0
		case "square":
			return Number.isFinite(data.side) && data.side > 0
	}
	return false
}
```

## With agents

The build is quiet when everything precompiles, helpers included: ``const text = (max: number) => type(`0 < string <= ${max}`)`` precompiles at each call passing it values the build can read, like `text(50)`. Where it can't precompile a definition and the fix is clear, the build fails, with the file, line and column, what it couldn't do, why, and how to fix it:

```
src/forms.ts:8:16  text(limit) cannot be precompiled
  `limit` is a parameter of makeField (src/forms.ts:7:27); its value is known only at runtime
  Write the definition where makeField is called, with the value it passes for `limit`, so the build precompiles each call.
```

To shorten the build-fix loop:

- Run [`arktype-precompile --check`](/docs/precompile/setup#check-an-existing-project) to list every definition the build would refuse, without bundling.
- Add the [ESLint rule](/docs/precompile/setup#eslint) so the same errors show in the editor and in lint runs.
- Run tests in [shadow mode](/docs/precompile/advanced#shadow-mode), which fails a test wherever a precompiled validator would behave otherwise than arktype.
- Give your agent the [ArkType skill](/docs/agents) so it writes definitions the build accepts on the first try.

## Build time

Precompiling moves creating your Types from your program's startup to your build, so a build takes longer. <Claim id="buildTimeApp" />

- <Claim id="buildTimeProduction" />
- <Claim id="buildTimeDev" />
- <Claim id="buildTimeWatch" />

<Claim id="buildTimeMedium" /> Turbopack runs the loader in a pool of processes,
once for the client and once for the server. `next dev` precompiles each module
for each, where one process of `next build` precompiles its project once.

## How a validator differs

A standalone validator validates, asserts and implements Standard Schema as the Type it replaces does. It doesn't compose or introspect: it lacks methods like `.and` and `.extends`, and its error messages say what failed without printing the value. The build fails wherever it sees your program rely on what a validator lacks. See [Validators](/docs/precompile/validators).

If you need the whole Type API at runtime, build with `runtime: "arktype"`: arktype ships, and each Type the build could precompile skips compiling at runtime. [Dynamic vs Precompiled](/docs/precompile/dynamic-vs-precompiled) compares the three side by side.

---

### Ark Docs Content Docs Regex Index (`ark/docs/content/docs/regex/index.mdx`)

---
title: Overview
description: Install ArkRegex and see what it infers from the strings you already pass to new RegExp().
---

`regex` takes the same arguments as `new RegExp()` and returns a `RegExp` typed with the strings it matches, its captures and its flags:

```ts
import { regex } from "arkregex"

const ok = regex("^ok$", "i")
//    ^? Regex<"ok" | "oK" | "Ok" | "OK", { flags: "i" }>

const date = regex("^(\\d{4})-(\\d{2})-(\\d{2})$")
//    ^? Regex<`${number}-${number}-${number}`, { captures: [`${number}`, `${number}`, `${number}`] }>
```

`.exec()` returns typed captures:

```ts
import { regex } from "arkregex"

const date = regex("^(?<year>\\d{4})-(?<month>\\d{2})$")

const match = date.exec("2026-10")

if (match) {
	const month = match.groups.month
	//    ^? `${number}`
}
```

At runtime, `regex(src, flags)` is `new RegExp(src, flags)`. The result is a plain `RegExp`, and `Regex` exists only in your types, so the package adds one function to your bundle.

## Installation

<InstallationTabs pkg="arkregex" />

Performs best with TypeScript 5.9 or later, including TypeScript 7.

If you're upgrading, [Upgrading](/docs/upgrading#arkregex) lists what changed in inference.

## Features

- **Types**: infers the strings an expression matches, its positional and named captures and its flags. See [Inference](/docs/regex/inference).
- **Syntax**: parses the syntax `new RegExp()` accepts, including named groups, lookarounds, backreferences, modifiers and Unicode properties. A few valid patterns are rejected and a few invalid ones aren't caught; see [what isn't checked](/docs/regex/errors#what-isnt-checked).
- **Errors**: mistakes like an unclosed group or a reference to a group that doesn't exist are [type errors](/docs/regex/errors).
- **No runtime cost**: the only code that runs is `new RegExp()`.

## Syntax highlighting

The [ArkType extension](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkdark) highlights the expression inside `regex` calls.

## ArkType

`arktype` re-exports `regex` and the `Regex` type, so if you use ArkType you don't need to install `arkregex` separately:

```ts
import { regex, type Regex } from "arktype"
```

ArkType also uses ArkRegex to infer its own regex literals, so `type("/^\\d{5}$/")` infers ``Type<`${number}`>``. See [ArkType](/docs/regex/arktype).

---

### Ark Docs Content Docs Sets Index (`ark/docs/content/docs/sets/index.mdx`)

---
title: Overview
description: Read arktype Types, Standard JSON Schemas and JSON Schemas as sets of values, relate and combine them, and write them back out as JSON Schema.
---

`arksets` treats a schema as the set of values it accepts. It reads schemas from any format, relates and combines them with the same algebra ArkType reduces its own Types with, and writes the result back out as JSON Schema:

```ts
import { intersect, isSubset, toJsonSchema } from "arksets"

const V1 = {
	type: "object",
	properties: {
		id: { type: "string" },
		age: { type: "integer", minimum: 0 }
	},
	required: ["id", "age"]
} as const

const V2 = type({ id: "string", "age?": "number" })

// V2 is backwards compatible: it accepts everything V1 did
isSubset(V1, V2) // true
// but not the other way around: V2 accepts { id: "a" }
isSubset(V2, V1) // false

const Capped = intersect(V2, {
	type: "object",
	properties: { age: { maximum: 120 } }
})

Capped.expression // "{ id: string, age?: number <= 120 }"

toJsonSchema(Capped)
```

```json
{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"type": "object",
	"properties": {
		"id": { "type": "string" },
		"age": { "type": "number", "maximum": 120 }
	},
	"required": ["id"]
}
```

Use it to check that a new version of an API schema still accepts what the old one did, to find out whether two schemas can ever accept the same value, to merge schemas from different libraries into one, or to normalize any of them to JSON Schema.

## Installation

<InstallationTabs pkg="arksets" />

`arktype` depends on `arksets` already, but only imports [the engine](#the-engine). Install it yourself to import the functions on these pages.

## Schemas

Every function takes a `Schema`, which can be any of:

- a **Root**: an `@ark/schema` node, which every arktype Type is. It's read losslessly, never through JSON Schema.
- a **[Standard JSON Schema](https://standardschema.dev/json-schema)**: a schema whose `~standard` has `jsonSchema`, like one from zod 4.2.0 or later. `arksets` reads its draft 2020-12 JSON Schema, so what that can't express, like zod's refinements, transforms and `undefined`, is invisible to every function here. Pass any other library's schema as its JSON Schema, like `z.toJSONSchema(schema)` before zod 4.2.0.
- a **JSON Schema**: an object or a boolean, read as [Keyword support](/docs/json-schema/support) describes.

Every argument can be in a different format. Results that are sets are Roots, so you can validate with them, print them and pass them back in:

```ts
import { intersect } from "arksets"

const Port = intersect({ type: "integer" }, type("number >= 1024"))

Port.expression // "number % 1 >= 1024"
Port(8080) // 8080
Port.allows(80) // false
```

## parse

`parse` reads a schema into a Root. Every other function calls it on its arguments, so you only need it to read a schema with options:

```ts
import { parse } from "arksets"

const Query = type({
	page: type("string").pipe(s => Number(s), type("number.integer >= 1"))
})

parse(Query).expression // "{ page: string }"
parse(Query, { io: "out" }).expression // "{ page: number % 1 >= 1 }"
```

| option | default           | effect                                                                                        |
| ------ | ----------------- | --------------------------------------------------------------------------------------------- |
| `io`   | `"in"`            | which side of a schema that transforms to read: what it accepts, or what it outputs (`"out"`) |
| `root` | the schema itself | the document a JSON Schema's `#/...` refs resolve against, like an OpenAPI document           |

```ts
import { parse } from "arksets"

const openApi = {
	components: {
		schemas: {
			User: {
				type: "object",
				properties: { name: { type: "string" } },
				required: ["name"]
			}
		}
	}
}

const User = parse({ $ref: "#/components/schemas/User" }, { root: openApi })

User.allows({ name: "Ada" }) // true
```

A schema object is read once per `io` and cached, so passing the same object to many functions doesn't read it again.

`parse` throws a `ParseError` for anything that isn't one of the three formats, for a Standard Schema that doesn't implement Standard JSON Schema or whose `~standard.jsonSchema` throws, like zod's for `z.date()` (the library's error is its `cause`), and for a JSON Schema it can't read exactly, like one with a remote `$ref` or `unevaluatedProperties`.

## arktype Types and JSON Schema

ArkType's `object` includes arrays, like TypeScript's. JSON Schema's `"object"` excludes them. An arktype Type is read with its own meaning, so it accepts values a JSON Schema with the same properties doesn't:

```ts
import { isSubset } from "arksets"

const User = type({ name: "string" })

const JsonUser = {
	type: "object",
	properties: { name: { type: "string" } },
	required: ["name"]
} as const

isSubset(JsonUser, User) // true
// User accepts Object.assign([], { name: "" })
isSubset(User, JsonUser) // false
isSubset(User.toJsonSchema(), JsonUser) // true
```

To compare a Type with JSON's meaning, pass its `.toJsonSchema()`.

## The engine

Importing `arksets` also installs the set algebra `@ark/schema` reduces nodes and discriminates unions with, and that `.and()`, `.extends()`, `.toJsonSchema()` and the other relational methods use. `arktype` installs it from `arksets/internal`, so these functions stay out of its bundle. [Set algebra](/docs/internals/sets) describes what `@ark/schema` does without it.

`arksets/internal` exports the engine's own functions for `@ark/schema` and `arktype`. Like `@ark/schema`, it isn't semver-stable.

---

### Ark Docs Content Docs (Arktype) Configuration Index (`ark/docs/content/docs/(arktype)/configuration/index.mdx`)

---
title: Configuration
description: 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:

```ts title="config.ts"
import { configure } from "arktype/config"

configure({ numberAllowsNaN: true })
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

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

<Callout type="warn" title="Configure 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"`.
</Callout>

### Scope

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

```ts
const $ = scope(
	{ User: { age: "number < 100" } },
	{ max: { actual: () => "unacceptably large" } }
)

// ArkErrors: age must be less than 100 (was unacceptably large)
$.export().User({ age: 101 })

// ArkErrors: age must be at most 100 (was unacceptably large)
$.type({ age: "number <= 100" })({ age: 101 })
```

### Type

`.configure` adds [metadata](/docs/expressions#meta), like a `description` or [error parts](#error-messages), to a Type. It applies wherever that Type is referenced, but not to the Types inside it:

```ts
// don't print the password
const Password = type("string >= 8").configure({ actual: "" })

const User = type({
	email: "string.email",
	password: Password
})

// ArkErrors: password must be at least length 8
User({ email: "david@arktype.io", password: "ez123" })
```

## Options

| option                                                      | default                                            | levels               |
| ----------------------------------------------------------- | -------------------------------------------------- | -------------------- |
| [`onUndeclaredKey`](#onundeclaredkey)                       | `"ignore"`                                         | global, type (`"+"`) |
| [`exactOptionalPropertyTypes`](#exactoptionalpropertytypes) | `true`                                             | global, scope        |
| [`numberAllowsNaN`](#numberallowsnan)                       | `false`                                            | global               |
| [`numberAllowsInfinity`](#numberallowsinfinity)             | `false`                                            | global               |
| [`dateAllowsInvalid`](#dateallowsinvalid)                   | `false`                                            | global               |
| [`jitless`](#jitless)                                       | `false`, or `true` where `new Function` is blocked | global, scope        |
| [`onFail`](#onfail)                                         | `null`, which returns `ArkErrors`                  | global, scope        |
| [`errors`](#errors)                                         | `"all"`                                            | global, scope        |
| [`mutatesInput`](#mutatesinput)                             | `false`                                            | global, scope        |
| [`keywords`](#keywords)                                     | `{}`                                               | global               |
| [`locale`](#locale)                                         | `en`                                               | global               |
| [an error code](#by-code), like `divisor`                   | ArkType's messages                                 | global, scope        |
| [`toJsonSchema`](#tojsonschema)                             | draft 2020-12, throwing for what it can't express  | global, scope        |

A Type's own options are its [metadata](/docs/expressions#meta), including the [parts of its errors](#error-messages).

## Error messages

Each error message is built from parts. Configure the part you want to change, and ArkType keeps composing the rest, including messages for unions and intersections. `expected`, `actual`, `problem` and `message` each take a string or a function. See [Errors](/docs/errors) for what an error contains.

### description

What follows "must be" in a message. Other parts and the Type's `.description` reuse it, so it should be your first choice:

```ts
const Even = type("number % 2").describe("an even number")

// ArkErrors: must be an even number
Even(3)
```

### 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`:

```ts
const 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 goes inside "(was …)". A message doesn't say what the value was unless an `actual` is configured, except a missing key's, which reads "(was missing)", though an error's `actual` still describes its data, like "5" or "an object", for a `problem` or `message` you write. An empty string omits it. A function receives the data, then the error:

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

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

### problem

The whole sentence after the path, like "must be a string", and the text a [Standard Schema](/docs/standard-schema) consumer, like a form library, shows beside a field as its issue's `message`. A union's problem lists each branch's path from its own. A function receives the error, including its `expected` and `actual`. It may not apply to the errors of a union:

```ts
const Name = type("string").configure({
	problem: ctx => `isn't ${ctx.expected}`
})

// ArkErrors: isn't a string
Name(5)
```

### message

The whole message, including the path, read from the errors calling a Type returns, their `summary` and what `.assert()` throws. It doesn't reach Standard Schema issues, whose `message` is the [`problem`](#problem). A function receives the error, including its `problem`. It may not apply to the errors of a union:

```ts
const User = type({
	password: "string >= 8"
}).configure({
	message: ctx => `${ctx.propString || "(root)"}: ${ctx.problem}`
})

// ArkErrors: (root): must be an object
User("ez123")

// .configure applies only at the root, so the nested error is unchanged
// ArkErrors: password must be at least length 8
User({ password: "ez123" })
```

Each function also receives the active [locale](/docs/i18n#your-own-messages) as its last argument, so it can write its text in the language a message is read in.

### By code

Globally or in a scope, configure errors by their [code](/docs/errors#error-codes). A function's `ctx` is typed by its code:

```ts
const mod = type.module(
	{ isEven: "number % 2" },
	{
		divisor: {
			expected: ctx => `% ${ctx.rule} !== 0`,
			problem: ctx => `${ctx.actual} ${ctx.expected}`
		}
	}
)

// ArkErrors: 3 % 2 !== 0
mod.isEven(3)
```

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

```ts
const $ = scope(
	{ User: { "+": "reject", name: "string" } },
	{ undeclared: { problem: "isn't allowed" } }
)

// ArkErrors: age isn't allowed
$.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:

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

configure({ locale: de })
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

// ArkErrors: muss eine Zeichenkette sein, ist aber eine Zahl
type.string(5)
```

`locale` can also be a function that returns a locale each time a message is read. See [i18n](/docs/i18n).

## keywords

Configure built-in keywords like `string.email` by name. Each takes a description or the same options as [`.configure`](#type):

```ts title="config.ts"
import { configure } from "arktype/config"

configure({
	keywords: {
		string: "text",
		"string.email": {
			actual: () => "definitely fake"
		}
	}
})
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

const 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" })
```

## 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 [`"+"`](/docs/objects#properties-undeclared), or change the default globally:

```ts title="config.ts"
import { configure } from "arktype/config"

configure({ onUndeclaredKey: "delete" })
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

const UserForm = type({
	name: "string"
})

// { name: "Alice" }
UserForm({ name: "Alice", age: "42" })
```

## exactOptionalPropertyTypes

By default, ArkType treats optional keys as TypeScript does with [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig/#exactOptionalPropertyTypes): an optional key can be omitted, but not set to `undefined`.

```ts
const 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:

```ts title="config.ts"
import { configure } from "arktype/config"

configure({ exactOptionalPropertyTypes: false })
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

const MyObj = type({
	"key?": "number",
	withDefault: "number = 5"
})

// { key: undefined, withDefault: 5 }
MyObj({ key: undefined, withDefault: undefined })
```

With `false`, an explicit `undefined` at a key with a default is replaced by the default, as a missing key is. Treating `null` as missing is tracked in [#1283](https://github.com/arktypeio/arktype/issues/1283).

## numberAllowsNaN

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

```ts
const 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:

```ts
const 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`:

```ts title="config.ts"
import { configure } from "arktype/config"

configure({ dateAllowsInvalid: true })
```

```ts title="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 up to about 30x slower per call on a plain object, and 3x to 5x on invalid data or a morph.

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](/docs/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`:

```ts title="config.ts"
import { configure } from "arktype/config"

configure({ jitless: true })
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

// will not be compiled
const 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](/docs/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`

```ts title="config.ts"
import { configure } from "arktype/config"
import "arktype/errors"

configure({ errors: "none" })
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

const User = type({ name: "string", age: "number" })

// ArkErrors: is invalid
const 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. It's still an instance of `type.errors`, `.assert()` throws a `TraversalError` saying `is invalid`, and its message isn't [localized](#locale). 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 to that Scope's Types, including where another Scope references them.

A [precompiled](/docs/precompile/options#errors) 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

```ts title="config.ts"
import { configure } from "arktype/config"
import "arktype/mutatesInput"

configure({ mutatesInput: true })
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

const User = type({ name: "string.trim", role: "string = 'member'" })

const data = { name: " Ada " }

// true, and data is now { name: "Ada", role: "member" }
const isData = Object.is(User(data), 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](/docs/precompile/options#mutatesinput) build takes `mutatesInput` as an option.

## onFail

To throw on every failed validation, or transform its result some other way, configure `onFail`. Declare its return type on `ArkEnv` so calls are typed to match:

```ts title="config.ts"
import { configure } from "arktype/config"

const config = configure({
	onFail: errors => errors.throw()
})

declare global {
	interface ArkEnv {
		onFail: typeof config.onFail
	}
}
```

```ts title="app.ts"
import "./config.ts"
import { type } from "arktype"

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

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

`onFail` can also be passed to a scope.

## toJsonSchema

`toJsonSchema` sets the defaults for `.toJsonSchema()`, like its target and how to handle what JSON Schema can't express. See [JSON Schema](/docs/json-schema/to-json-schema).

<AnchorAliases fallback-codes />

## metadata

<AnchorAliases custom />

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

```ts
// add this anywhere in your project
declare global {
	interface ArkEnv {
		meta(): {
			// meta properties should always be optional
			secretIngredient?: string
		}
	}
}

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

## 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:

```ts
declare global {
	interface ArkEnv {
		prototypes(): MySpecialClass
	}
}

class MySpecialClass {}

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

---

### Ark Docs Content Docs (Arktype) Ecosystem Index (`ark/docs/content/docs/(arktype)/ecosystem/index.mdx`)

---
title: Ecosystem
description: Community projects built on ArkType, for environment variables, Drizzle codegen and binary serialization.
---

These projects are maintained by their authors, not the ArkType team. For libraries that accept a Type directly, see [Integrations](/docs/integrations).

## ArkEnv

[ArkEnv](https://arkenv.js.org) validates your environment variables with an ArkType definition and gives you a typed `env` object, with strings like `"3000"` already parsed into the types you declared.

It works like [T3 Env](https://env.t3.gg), built around ArkType definitions, and adds keywords for common variables like `string.host` and `number.port`.

Scaffold with `npx arkenv init` and import from `@arkenv/core` (`arkenv` on npm is the CLI).

```ts
// @noErrors
import arkenv from "@arkenv/core"

const env = arkenv({
	HOST: "string.host",
	PORT: "number.port",
	NODE_ENV: "'development' | 'production' | 'test' = 'development'"
})

// process.env is validated and parsed when this runs
env.HOST // string
env.PORT // number
env.NODE_ENV // "development" | "production" | "test"
```

## DRZL

[DRZL](https://use-drzl.github.io/drzl) generates code from your Drizzle ORM schemas: ArkType validators, typed services and routers that reuse them.

```ts
// @noErrors
// drzl.config.ts
import { defineConfig } from "@drzl/cli/config"

export default defineConfig({
	schema: "src/db/schemas/index.ts",
	outDir: "src/api",
	generators: [
		// 1) ArkType validators
		{ kind: "arktype", path: "src/validators/arktype", schemaSuffix: "Schema" },

		// 2) Routers (oRPC adapter), reusing ArkType schemas
		{
			kind: "orpc",
			template: "@drzl/template-orpc-service",
			includeRelations: true,
			outputHeader: { enabled: true },
			validation: {
				useShared: true,
				library: "arktype",
				importPath: "src/validators/arktype",
				schemaSuffix: "Schema"
			}
		},
		// 3) Typed services (Drizzle-aware or stub)
		{
			kind: "service",
			path: "src/services",
			dataAccess: "drizzle", // or 'stub'
			dbImportPath: "src/db/connection",
			schemaImportPath: "src/db/schemas"
		}
	]
})
```

> For more details, see the [Getting Started guide](https://use-drzl.github.io/drzl/guide/getting-started.html).

## shorn

[shorn](https://shorn.dev) turns an ArkType type into compact binary serialization. Field names and type tags stay out of the payload because the type already provides them, so there is no schema language to learn and nothing to generate.

ArkType 2.1.28 and newer implements both [Standard Schema](https://standardschema.dev/schema) and [Standard JSON Schema](https://standardschema.dev/json-schema), so a type can be passed straight to `encode`. Validation runs on encode and again on decode.

```ts
// @noErrors
import { type } from "arktype"
import { decode, encode } from "@chichurita/shorn"

const Person = type({
	name: "string",
	age: "number.integer >= 0",
	sex: "'M' | 'F' | 'X'"
})

const bytes = encode(Person, { name: "Grace", age: 45, sex: "F" })
bytes.length // 8, where the same record is 35 bytes of minified JSON

decode(Person, bytes) // typed and validated
```

> ArkType objects are open by default, so shorn rejects undeclared properties during encoding rather than dropping data. Use `"+": "delete"` to strip expected extras. See the [ArkType guide](https://shorn.dev/validators/arktype/) for the details.

---

### Ark Docs Content Docs (Arktype) Expressions Index (`ark/docs/content/docs/(arktype)/expressions/index.mdx`)

---
title: Expressions
description: Combine, refine, transform and annotate types with operators like unions, intersections, narrows, pipes, brands and metadata.
---

An expression combines or modifies other definitions. Most expressions can be written four ways:

- **string**: embedded in a string definition, like `"string | number"`
- **fluent**: a method on a `Type`, like `type.string.or(type.number)`
- **tuple**: an array definition, like `["string", "|", "number"]`
- **args**: the same elements passed to `type` as arguments, like `type("string", "|", "number")`

They're interchangeable, so use whichever reads best. Where an operand is a function or a value like a symbol, use the fluent, tuple or args form.

| Expression                                     | String             | Fluent                   | Tuple / args            |
| ---------------------------------------------- | ------------------ | ------------------------ | ----------------------- |
| [intersection](/docs/expressions#intersection) | `"a & b"`          | `.and(b)`                | `[a, "&", b]`           |
| [union](/docs/expressions#union)               | `"a \| b"`         | `.or(b)`                 | `[a, "\|", b]`          |
| [array](/docs/objects#arrays)                  | `"a[]"`            | `.array()`               | `[a, "[]"]`             |
| [keyof](/docs/objects#properties-keyof)        | `"keyof a"`        | `.keyof()`               | `["keyof", a]`          |
| [brand](/docs/expressions#brand)               | `"a#name"`         | `.brand("name")`         |                         |
| [narrow](/docs/expressions#narrow)             |                    | `.narrow(fn)`            | `[a, ":", fn]`          |
| [filter](/docs/expressions#filter)             |                    | `.filter(fn)`            |                         |
| [pipe](/docs/expressions#pipe)                 |                    | `.pipe(fn)`              | `[a, "=>", fn]`         |
| [to](/docs/expressions#to)                     | `"a \|> b"`        | `.to(b)`                 | `[a, "\|>", b]`         |
| [unit](/docs/expressions#unit)                 | a literal, `"'a'"` | `type.unit(value)`       | `["===", value]`        |
| [meta](/docs/expressions#meta)                 |                    | `.configure(meta)`       | `[a, "@", meta]`        |
| [instanceof](/docs/objects#instanceof)         |                    | `type.instanceOf(Class)` | `["instanceof", Class]` |

Optional (`?`), defaultable (`=`) and spread (`...`) definitions only apply to properties and tuple elements. They're covered on the [objects](/docs/objects) page.

## Intersection

Like its TypeScript counterpart, an intersection creates a `Type` that enforces the constraints of both operands.

<SyntaxTabs>
	<SyntaxTab string>

```ts
// an email address at arktype.io
const ArkEmail = type("string.email & /@arktype\\.io$/")

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// an email address at arktype.io
const ArkEmail = type("string.email").and(/@arktype\.io$/)

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
// an email address at arktype.io
const ArkEmail = type(["string.email", "&", /@arktype\.io$/])

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
// an email address at arktype.io
const ArkEmail = type("string.email", "&", /@arktype\.io$/)

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

    </SyntaxTab>

</SyntaxTabs>

<Callout type="warn" title="To combine properties, merge instead">

Intersecting objects is more work to compute than [merging](/docs/objects#merge) them, both when the type is created and in your editor. Unless you need overlapping keys' values intersected, merge.

</Callout>

<AnchorAliases intersection-n-ary />
### n-ary

`type.and` intersects any number of definitions:

```ts
// Type<{ foo: string; bar: number; baz: string }>
const FooBarBaz = type.and(
	{ foo: "string" },
	{ bar: "number" },
	{ baz: "string" }
)
```

## Union

A union allows a value that satisfies either operand. ArkType discriminates unions automatically: where a value like its type or a literal key tells the branches apart, it checks that first instead of trying each branch, which keeps validation fast and errors specific. Where the discriminant can't place data, like a number where every branch is an object, each branch reports its own error, as in an undiscriminated union.

<SyntaxTabs>
	<SyntaxTab string>

```ts
const StringOrNumber = type("string | number")

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const StringOrNumber = type.string.or(type.number)

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const StringOrNumber = type(["string", "|", "number"])

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const StringOrNumber = type("string", "|", "number")

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

    </SyntaxTab>

</SyntaxTabs>

When no branch matches the discriminant, like a value of the wrong type here, the error's code is `discriminant`. See [errors](/docs/errors) for the fields it carries.

<AnchorAliases union-n-ary />
### n-ary

`type.or` unions any number of definitions:

```ts
// Type<string | number | { key: unknown }>
const Union = type.or(type.string, "number", { key: "unknown" })
```

<AnchorAliases union-morphs />

<Callout type="warn" title="A union that could transform the same input in different ways throws a ParseError">

```ts
// operands overlap, but neither transforms data
const Okay = type("number > 0").or("number < 10")

// an operand transforms data, but the inputs don't overlap
const AlsoOkay = type("string.numeric.parse").or({ box: "string" })

// ParseError: An unordered union of a type including a morph and a type with overlapping input is indeterminate
const Bad = type({ box: "string.numeric.parse" }).or({ box: "string" })
```

To fix it, make the inputs disjoint, e.g. by narrowing a morph's input, or pipe the union of their inputs to a single morph:

```ts
// only numeric strings are parsed, so no input reaches two branches
const Narrowed = type("string.numeric.parse | number | null")

// one morph decides how to transform each input
const Piped = type("unknown").pipe(v => (v === null ? v : Number(v)))
```

<details>
	<summary>Why this isn't allowed</summary>

`Bad` says two things about the same input:

- if `box` is a string, parse it as a number
- if `box` is a string, keep it as a string

The order of a union's branches doesn't affect its result, so there's no way to choose between them. The same applies when the transformed keys differ: `type({ a: "string.numeric.parse" }).or({ b: "string.numeric.parse" })` throws too, since an input like `{ a: "1", b: "2" }` matches both branches and each would parse a different key.

</details>

</Callout>

### extract / exclude [#extract-exclude]

`.extract()` keeps the branches of a union that are assignable to a definition, and `.exclude()` removes them, like TypeScript's `Extract` and `Exclude`:

```ts
const Primitive = type("string | number | boolean")

// Type<number | boolean>
const NumberOrBoolean = Primitive.extract("number | boolean")

// Type<number | boolean>
const NotString = Primitive.exclude("string")
```

In a definition, use the `Extract` and `Exclude` [generics](/docs/generics#keywords), e.g. `"Exclude<'a' | 'b' | 0, string>"`.

## Brand

A brand adds a type-only tag to a type, so the only values that satisfy it are those you validated with it.

<SyntaxTabs>
	<SyntaxTab string>

```ts
// @errors: 2322
const Even = type("(number % 2)#even")
type Even = typeof Even.infer

const good: Even = Even.assert(2)
// TypeScript: Type 'number' is not assignable to type 'Brand<number, "even">'
const bad: Even = 5
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// @errors: 2322
const Even = type.number.divisibleBy(2).brand("even")
type Even = typeof Even.infer

const good: Even = Even.assert(2)
// TypeScript: Type 'number' is not assignable to type 'Brand<number, "even">'
const bad: Even = 5
```

    </SyntaxTab>

</SyntaxTabs>

A brand changes nothing at runtime. The `Brand` type it infers is exported from `arktype`.

For more on branding in general, see [this article](https://www.learningtypescript.com/articles/branded-types) by [Josh Goldberg](https://github.com/joshuakgoldberg).

## Narrow

A narrow adds custom validation to a type. Return `true` to accept the value, or call `ctx.mustBe()` or `ctx.reject()` to reject it with a message. The [intro](/docs/intro/adding-constraints#narrow) walks through an example.

<SyntaxTabs>
	<SyntaxTab fluent>

```ts
const Palindrome = type("string").narrow(
	(s, ctx) => s === [...s].reverse().join("") || ctx.mustBe("a palindrome")
)

// ArkErrors: must be a palindrome
Palindrome("arktype")
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const Palindrome = type([
	"string",
	":",
	(s, ctx) => s === [...s].reverse().join("") || ctx.mustBe("a palindrome")
])

// ArkErrors: must be a palindrome
Palindrome("arktype")
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const Palindrome = type(
	"string",
	":",
	(s, ctx) => s === [...s].reverse().join("") || ctx.mustBe("a palindrome")
)

// ArkErrors: must be a palindrome
Palindrome("arktype")
```

    </SyntaxTab>

</SyntaxTabs>

`ctx.reject()` can also set the error's `path` and `actual`, e.g. to report a mismatch at the right key without printing a password:

```ts
const Form = type({
	password: "string",
	confirmPassword: "string"
}).narrow(
	(data, ctx) =>
		data.password === data.confirmPassword ||
		ctx.reject({
			expected: "identical to password",
			actual: "",
			path: ["confirmPassword"]
		})
)

// ArkErrors: confirmPassword must be identical to password
Form({ password: "arktype", confirmPassword: "artkype" })
```

If a narrow's return type is a type predicate, the `Type` infers it:

```ts
// Type<`ark${string}`>
const ArkString = type("string").narrow(
	(data, ctx): data is `ark${string}` =>
		data.startsWith("ark") || ctx.reject("a string starting with 'ark'")
)
```

The [traversal API](/docs/traversal-api) documents everything `ctx` can do.

## Filter

`filter` is like `narrow`, but checks a type's **input** instead of its output. The difference matters when the type transforms its input:

- **`narrow`** checks the **output**, after morphs run
- **`filter`** checks the **input**, before morphs run

```ts
const ShortNumeric = type("string.numeric.parse").filter(
	// s is the input string, not the parsed number
	(s, ctx) => s.length <= 10 || ctx.reject("at most 10 characters")
)

// 123
ShortNumeric("123")

// ArkErrors: must be at most 10 characters
ShortNumeric("12345678901")
```

Like `narrow`, a type predicate returned by a filter is inferred, here as the type's input.

<AnchorAliases morph />
## Pipe

A pipe transforms data after it is validated, through one or more functions called **morphs**. The [intro](/docs/intro/morphs-and-more) walks through examples.

<SyntaxTabs>
	<SyntaxTab fluent>

```ts
// Type<(In: string) => Out<string>>
const TrimStart = type("string").pipe(str => str.trimStart())
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
// Type<(In: string) => Out<string>>
const TrimStart = type(["string", "=>", str => str.trimStart()])
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
// Type<(In: string) => Out<string>>
const TrimStart = type("string", "=>", str => str.trimStart())
```

    </SyntaxTab>

</SyntaxTabs>

A morph receives the validated value itself rather than a copy, so a morph that mutates its argument mutates the caller's data. ArkType's own transforms, like defaults, copy each object they change and share every untransformed value with the input, and input nothing transforms is returned as is. The exception is an instance of a builtin class, like a `Date`, `Map` or function, which keeps its state in internal slots and is transformed in place. [`mutatesInput`](/docs/configuration#mutatesinput) writes transforms into the data instead.

```ts
const T = type({ a: "string.trim", b: { c: "string" } })
const input = { a: " x ", b: { c: "y" } }

const out = T.assert(input)

out === input // false
out.b === input.b // true
```

### To

A morph can return `ArkErrors` to fail validation, so a `Type` works as a morph: it validates the previous output. The `to` operator pipes to a definition without wrapping it in `type`:

<SyntaxTabs>
	<SyntaxTab string>

```ts
// Type<(In: string) => To<number>>
const ParseEven = type("string.numeric.parse |> number % 2")

// ArkErrors: must be even
ParseEven("3")
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// Type<(In: string) => To<number>>
const ParseEven = type("string.numeric.parse").to("number % 2")

// ArkErrors: must be even
ParseEven("3")
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
// Type<(In: string) => To<number>>
const ParseEven = type(["string.numeric.parse", "|>", "number % 2"])

// ArkErrors: must be even
ParseEven("3")
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
// Type<(In: string) => To<number>>
const ParseEven = type("string.numeric.parse", "|>", "number % 2")

// ArkErrors: must be even
ParseEven("3")
```

    </SyntaxTab>

</SyntaxTabs>

`.to("number % 2")` is the same as `.pipe(type("number % 2"))`.

<AnchorAliases pipe-n-ary />
### n-ary

`.pipe()` accepts any number of morphs and types. `type.pipe()` does the same without a `Type` to start from:

```ts
// Type<(In: string) => To<string>>
const TrimStartNonEmpty = type.pipe(
	type.string,
	s => s.trimStart(),
	type.string.atLeastLength(1)
)

// ArkErrors: must be non-empty
TrimStartNonEmpty("   ")
```

## Unit

A [literal](/docs/primitives#number-literals) is the simplest way to allow one exact primitive value. To allow a value a string can't embed, like a `symbol`, use `type.unit` or `===`:

<SyntaxTabs>
	<SyntaxTab fluent>

```ts
const mySymbol = Symbol()

const ExactValue = type.unit(mySymbol)
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const mySymbol = Symbol()

const ExactValue = type(["===", mySymbol])
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const mySymbol = Symbol()

const ExactValue = type("===", mySymbol)
```

    </SyntaxTab>

</SyntaxTabs>

## Enumerated

`type.enumerated` allows any of a list of values. With one value, it's the same as `type.unit`.

<SyntaxTabs>
	<SyntaxTab fluent>

```ts
const mySymbol = Symbol()

const ExactValueFromSet = type.enumerated(1337, true, mySymbol)
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const mySymbol = Symbol()

const ExactValueFromSet = type(["===", 1337, true, mySymbol])
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const mySymbol = Symbol()

const ExactValueFromSet = type("===", 1337, true, mySymbol)
```

    </SyntaxTab>

</SyntaxTabs>

## valueOf

`type.valueOf` allows the values of a TypeScript `enum` or an enum-like object:

```ts
enum TsEnum {
	numeric = 1
}

// Type<TsEnum.numeric>
const EnumType = type.valueOf(TsEnum)
```

It is almost the same as `type.enumerated(...Object.values(o))`. The difference is an entry whose key is another entry's numeric value, mapping back to that entry's key. That's how TypeScript compiles a numeric `enum`, so `valueOf` skips the reverse entry:

```ts
// what TsEnum compiles to
const equivalentObject = {
	numeric: 1,
	"1": "numeric"
} as const

// allows only 1, though it infers Type<1 | "numeric">
const EquivalentType = type.valueOf(equivalentObject)
```

<Callout type="info" title="Prefer enumerated">

TypeScript is moving away from features that emit JavaScript, like `enum`, which [`--erasableSyntaxOnly`](https://www.typescriptlang.org/tsconfig/#erasableSyntaxOnly) disallows. `type.valueOf` is for code that already uses `enum`. Otherwise, list values with [`type.enumerated`](/docs/expressions#enumerated) or a literal union.

</Callout>

## fn

`type.fn` wraps a function so its parameters, and optionally its return value, are validated when it's called. Parameters use tuple syntax. Put a return type after `":"`.

```ts
// @errors: 2345
const len = type.fn("string | unknown[]", ":", "number")(s => s.length)

len("foo") // 3
len([1, 2]) // 2

// TraversalError: [0] must be a string or an array
len(true)
```

The result is a `TypedFn`, which is introspectable:

```ts
const len = type.fn("string | unknown[]", ":", "number")(s => s.length)

len.expression // "(string | Array) => number"
len.params.expression // "[string | Array]"
len.returns.expression // "number"
```

Parameters can be defaultable, optional or variadic:

```ts
const greet = type.fn("string = 'world'")(name => `Hello, ${name}!`)

greet() // "Hello, world!"

const join = type.fn("...", "string[]")((...parts) => parts.join(","))

join("a", "b") // "a,b"
```

Without a return type, the return type is inferred from the implementation and not validated.

## Meta

Metadata attaches information to a type. ArkType reads some of it, like `description`, which error messages use. You can read the rest from the type's `meta`.

<SyntaxTabs>
	<SyntaxTab fluent>

```ts
const SpecialString = type("string").configure({
	description: "a special string"
})

// .describe() is shorthand for a description
const SpecialNumber = type("number").describe("a special number")

// ArkErrors: must be a special number
SpecialNumber("five")
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const SpecialString = type([
	"string",
	"@",
	{
		description: "a special string"
	}
])

// a string is shorthand for a description
const SpecialNumber = type(["number", "@", "a special number"])

// ArkErrors: must be a special number
SpecialNumber("five")
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const SpecialString = type("string", "@", {
	description: "a special string"
})

// a string is shorthand for a description
const SpecialNumber = type("number", "@", "a special number")

// ArkErrors: must be a special number
SpecialNumber("five")
```

    </SyntaxTab>

</SyntaxTabs>

An object definition can hold its own metadata under an `"@"` key:

```ts
const User = type({
	"@": "a user",
	name: "string"
})

// ArkErrors: must be a user
User(5)
```

A configured description, like any message you configure, takes precedence over the [locale](/docs/i18n#your-own-messages), so it isn't translated.

The `keyword` key is reserved: built-in keywords set `meta.keyword` to their name so a locale can find their phrase, and configuring a description removes it. Name your own metadata something else.

To configure only some of a type's nodes, pass a selector after the metadata:

<SyntaxTabs>
	<SyntaxTab fluent>

```ts
const Point = type({
	x: "number",
	y: "number"
}).configure(
	{ description: "a coordinate" },
	// every domain node: the object and both numbers
	"domain"
)

// ArkErrors: x must be a coordinate
Point({ x: "1", y: 2 })
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const Point = type([
	{
		x: "number",
		y: "number"
	},
	"@",
	{ description: "a coordinate" },
	// every domain node: the object and both numbers
	"domain"
])

// ArkErrors: x must be a coordinate
Point({ x: "1", y: 2 })
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const Point = type(
	{
		x: "number",
		y: "number"
	},
	"@",
	{ description: "a coordinate" },
	// every domain node: the object and both numbers
	"domain"
)

// ArkErrors: x must be a coordinate
Point({ x: "1", y: 2 })
```

    </SyntaxTab>

</SyntaxTabs>

Selectors are documented with [`select`](/docs/internals/nodes#select).

## Cast

A cast changes how a `Type` is inferred without changing what it validates:

<SyntaxTabs>
	<SyntaxTab string>

```ts
// any string, but the editor suggests "foo" and "bar"
type AutocompletedString = "foo" | "bar" | (string & {})

const MyObj = type({
	autocompletedString: "string" as type.cast<AutocompletedString>
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// any string, but the editor suggests "foo" and "bar"
type AutocompletedString = "foo" | "bar" | (string & {})

const MyObj = type({
	autocompletedString: type.string.as<AutocompletedString>()
})
```

    </SyntaxTab>

</SyntaxTabs>

## Parenthetical

Operators have the same precedence as in TypeScript, and parentheses group them the same way:

```ts
// Type<{ stringOrNumbers: string | number[]; stringsOrNumbers: (string | number)[] }>
const Groups = type({
	stringOrNumbers: "string | number[]",
	stringsOrNumbers: "(string | number)[]"
})
```

## this

`this` references the root of the definition it's in, which makes the type recursive:

```ts
const DisappointingGift = type({
	label: "string",
	"box?": "this"
})

const out = DisappointingGift({
	label: "foo",
	box: { label: "bar", box: {} }
})

if (out instanceof type.errors) {
	// ArkErrors: box.box.label must be a string (was missing)
	console.error(out.summary)
} else {
	// narrowed inference to arbitrary depth
	console.log(out.box?.box?.label)
	//                         ^?
}
```

In a scope, `this` is a `ParseError`. Reference the alias by name instead, as described in [cyclic types](/docs/scopes#cyclic-types):

```ts
const types = scope({
	DisappointingGift: {
		label: "string",
		"box?": "DisappointingGift"
	}
}).export()
```

---

### Ark Docs Content Docs (Arktype) Generics Index (`ark/docs/content/docs/(arktype)/generics/index.mdx`)

---
title: Generics
description: Declare definitions with parameters and instantiate them like TypeScript generics.
---

A generic is a definition with parameters. Instantiating it with a definition for each parameter returns a `Type`.

## Keywords

Like TypeScript's utility types, these generics are available in any definition:

<GenericKeywordTable />

Instantiate one in a string, or call it from `type.keywords`:

```ts
const One = type("Extract<0 | 1, 1>")

const Unfalse = type.keywords.Exclude("boolean", "false")
```

`Record` is also available as `type.Record`. Generics like `Pick` and `Partial` have [method equivalents](/docs/objects#properties-pick-omit) on object Types, such as `User.pick("name")`.

## Syntax

### Definition

Pass a string of parameter names in angle brackets, then a definition that references them:

```ts
const BoxOf = type("<t>", { box: "t" })

// Type<{ box: string }>
const StringBox = BoxOf("string")
```

`type.generic("t")({ box: "t" })` is equivalent.

### Constraints

Constrain a parameter with `extends`. Arguments must satisfy the constraint, and the definition can use the parameter wherever its constraint is allowed, like with the `>` operator here:

```ts
// @errors: 2345
const NonEmpty = type("<arr extends unknown[]>", "arr > 0")

// Type<number[]>
const NonEmptyNumbers = NonEmpty("number[]")

// ParseError: arr must be assignable to Array (was string)
NonEmpty("string")
```

With `type.generic`, pass a `[name, constraint]` tuple: `type.generic(["arr", "unknown[]"])("arr > 0")`.

### Scoped

In a [scope](/docs/scopes), declare parameters in the alias name:

```ts
const types = scope({
	"Box<t, u>": { box: "t | u" },
	BitBox: "Box<0, 1>"
}).export()

// ArkErrors: box must be 0 or 1
types.BitBox({ box: 2 })
```

### Recursive

A scoped generic can reference itself:

```ts
const types = scope({
	"Tree<t>": { value: "t", "children?": "Tree<t>[]" },
	NumberTree: "Tree<number>"
}).export()

// ArkErrors: children[0].value must be a number
types.NumberTree({ value: 1, children: [{ value: "2" }] })
```

## HKT

`generic()` with an `Hkt` class wraps a type-level TypeScript function as an ArkType generic. The function transforms the arguments at runtime, and the class's `body` describes the result at the type level. This is how `Partial` is implemented:

```ts
import { generic, Hkt } from "arktype"

const Partial = generic(["T", "object"])(
	args => args.T.partial(),
	class PartialHkt extends Hkt<[object]> {
		declare body: Partial<this[0]>
	}
)

// Type<{ a?: string }>
const PartialA = Partial({ a: "string" })
```

For more examples, see the [generic tests](https://github.com/arktypeio/arktype/blob/HEAD/ark/type/__tests__/generic.test.ts).

## External

To write a TypeScript function that accepts and returns Types, constrain a parameter with `type.Any`:

```ts
const createBox = <t extends string>(of: type.Any<t>) =>
	type({
		box: of
	})

// @ts-expect-error
createBox(type("number"))

// Type<{ box: string }>
const BoxType = createBox(type("string"))
```

To accept a definition instead, validate it with `type.validate` and infer the result with `type.instantiate`:

```ts
const createBox = <const def>(
	of: type.validate<def>
): type.instantiate<{ box: def }> =>
	type.raw({
		box: of
	}) as never

// Type<{ box: string }>
const BoxType = createBox("string")
```

TypeScript generics like these can be hard to get right. If yours isn't inferring as expected, see [the FAQ](/docs/faq#why-isnt-my-wrapper-generic-working).

---

### Ark Docs Content Docs (Arktype) Integrations Index (`ark/docs/content/docs/(arktype)/integrations/index.mdx`)

---
title: Integrations
description: Use a Type directly with tRPC, oRPC, Drizzle, React Hook Form, Hono, the MCP SDK and the AI SDK.
---

Most libraries on this page accept a [Standard Schema](/docs/standard-schema), so you pass a Type as-is with no adapter. Where a library also publishes an ArkType-specific adapter, its section shows the Standard Schema route first.

Any other library that accepts a Standard Schema works the same way. [standardschema.dev](https://standardschema.dev/schema#what-tools-frameworks-accept-speccompliant-schemas) keeps a list.

## tRPC

[tRPC](https://trpc.io/docs/server/validators) 11 accepts a Type as a procedure's input or output:

```ts
import { initTRPC } from "@trpc/server"
import { type } from "arktype"

const t = initTRPC.create()

const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

export const appRouter = t.router({
	createUser: t.procedure.input(User).mutation(({ input }) => input)
})
```

Invalid input is rejected with a `BAD_REQUEST` error before the resolver runs.

## oRPC

[oRPC](https://orpc.dev) accepts a Type the same way:

```ts
import { os } from "@orpc/server"
import { type } from "arktype"

const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

export const createUser = os.input(User).handler(({ input }) => input)
```

To generate an OpenAPI document, give oRPC's `OpenAPIGenerator` the converter from `@orpc/arktype`:

```ts
import { os } from "@orpc/server"
import { type } from "arktype"

const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

export const createUser = os.input(User).handler(({ input }) => input)
// ---cut---
import { experimental_ArkTypeToJsonSchemaConverter } from "@orpc/arktype"
import { OpenAPIGenerator } from "@orpc/openapi"

const generator = new OpenAPIGenerator({
	schemaConverters: [new experimental_ArkTypeToJsonSchemaConverter()]
})

const spec = await generator.generate({ createUser })
```

## Drizzle

Drizzle maintains [`drizzle-arktype`](https://orm.drizzle.team/docs/arktype), which creates Types from your tables:

```ts
import { createInsertSchema, createSelectSchema } from "drizzle-arktype"
import { integer, pgTable, serial, text } from "drizzle-orm/pg-core"

const users = pgTable("users", {
	id: serial().primaryKey(),
	name: text().notNull(),
	age: integer()
})

const User = createSelectSchema(users)
// Type<{ id: number; name: string; age: number | null }>

const NewUser = createInsertSchema(users)
// Type<{ name: string; id?: number; age?: number | null }>
```

`createUpdateSchema` is like `createInsertSchema` with every column optional. Integer columns also get their range, so `age` above must be a 32-bit integer.

## React Hook Form

[`@hookform/resolvers`](https://github.com/react-hook-form/resolvers) includes `standardSchemaResolver`:

```ts
import { standardSchemaResolver } from "@hookform/resolvers/standard-schema"
import { type } from "arktype"
import { useForm } from "react-hook-form"

const User = type({
	name: "string > 0",
	age: "number.integer >= 0"
})

export const useUserForm = () =>
	useForm({ resolver: standardSchemaResolver(User) })
```

The form's field values are typed from the Type's input, and `handleSubmit` receives its output. If you pass type arguments to `useForm` yourself, pass all three: `useForm<typeof User.inferIn, unknown, typeof User.infer>`.

The same package exports `arktypeResolver` from `@hookform/resolvers/arktype`, which behaves the same. `@hookform/resolvers` lists `arktype@^2` as an optional peer dependency, so npm refuses to install it beside a later major version of ArkType, whichever resolver you import, until you [override the peer](/docs/upgrading#npm-refuses-packages-that-peer-on-arktype-2). pnpm warns, and bun installs it as is.

## Hono

[`@hono/standard-validator`](https://github.com/honojs/middleware/tree/main/packages/standard-validator) validates a request's `json`, `form`, `query`, `param`, `header` or `cookie`:

```ts
import { sValidator } from "@hono/standard-validator"
import { type } from "arktype"
import { Hono } from "hono"

const User = type({
	name: "string",
	age: "number.integer >= 0"
})

const app = new Hono()

app.post("/users", sValidator("json", User), c => {
	const user = c.req.valid("json")
	return c.json({ message: `${user.name} is ${user.age}` })
})
```

Invalid requests get a 400 response with the issues as JSON. [`@hono/arktype-validator`](https://github.com/honojs/middleware/tree/main/packages/arktype-validator) provides an equivalent `arktypeValidator`, with a required peer dependency on `arktype@^2`, so npm needs the same [override](/docs/upgrading#npm-refuses-packages-that-peer-on-arktype-2) to install it.

To generate an OpenAPI document from your routes, [`hono-openapi`](https://github.com/rhinobase/hono-openapi) has a `validator` that accepts a Type, and a `resolver` for describing responses with one.

## MCP SDK

The [MCP TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/advanced/schema-libraries) accepts a Type as a tool's `inputSchema` or `outputSchema`:

```ts
import { McpServer } from "@modelcontextprotocol/server"
import { type } from "arktype"

const server = new McpServer({ name: "greeter", version: "1.0.0" })

server.registerTool(
	"greet",
	{
		description: "Greet someone by name",
		inputSchema: type({
			name: "string",
			"times?": "1 <= number.integer <= 5"
		})
	},
	async ({ name, times = 1 }) => ({
		content: [{ type: "text", text: `Hello, ${name}! `.repeat(times) }]
	})
)
```

The SDK sends clients the JSON Schema from [`~standard.jsonSchema`](/docs/standard-schema#standard-json-schema) and validates arguments with the Type before your handler runs. A call with `times: 9` returns an error result, and the handler doesn't run.

This needs `@modelcontextprotocol/server`, the SDK's second major version. The first, `@modelcontextprotocol/sdk`, accepts only Zod schemas.

To serve it over stdio, connect a transport from `@modelcontextprotocol/server/stdio`:

```ts
import { McpServer } from "@modelcontextprotocol/server"
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"

const server = new McpServer({ name: "greeter", version: "1.0.0" })
// server.registerTool(...)

await server.connect(new StdioServerTransport())
```

To serve it from a route handler, like a Next.js App Router route, `createMcpHandler` builds a server for each request, and its `fetch` answers it:

```ts title="app/api/mcp/route.ts"
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server"

const handler = createMcpHandler(() => {
	const server = new McpServer({ name: "greeter", version: "1.0.0" })
	// server.registerTool(...)
	return server
})

const serve = (request: Request) => handler.fetch(request)

export { serve as GET, serve as POST, serve as DELETE }
```

## AI SDK

The [AI SDK](https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data) accepts a Type wherever it takes a schema. For structured output:

```ts
import { generateText, Output } from "ai"
import { type } from "arktype"

const Recipe = type({
	name: "string",
	ingredients: type({ name: "string", amount: "string" }).array(),
	steps: "string[]"
})

const { output } = await generateText({
	model: "anthropic/claude-sonnet-5.5",
	output: Output.object({ schema: Recipe }),
	prompt: "Write a recipe for toast."
})
```

For a tool's input:

```ts
import { tool } from "ai"
import { type } from "arktype"

const weather = tool({
	description: "Get the weather in a city",
	inputSchema: type({ city: "string" }),
	execute: async ({ city }) => ({ city, celsius: 21 })
})
```

The model sees the JSON Schema from [`~standard.jsonSchema`](/docs/standard-schema#standard-json-schema), and the AI SDK validates its response with the Type. Parts of a Type with no JSON Schema equivalent, like a `narrow`, aren't described to the model, but its response is still checked against them. Structured output arrives as JSON, so use `string.date.iso.parse` rather than `Date` for a date.

## Precompiled validators

A [precompiled](/docs/precompile) validator validates through Standard Schema as a Type does, so tRPC, oRPC, Hono's validators, React Hook Form, TanStack Form and Router, Elysia, t3-env and Next.js server actions take one with nothing to set. The build bakes a JSON Schema into each validator it sees a library convert, so the MCP SDK, the AI SDK, Elysia's `@elysiajs/openapi`, hono-openapi and oRPC's `OpenAPIGenerator` with `@orpc/arktype` need nothing set either, as [`members`](/docs/precompile/options#members) describes. A library that defines Types itself needs [`dependencies`](/docs/precompile/options#dependencies) set:

| Library                                                       | Set in `ark.json` (or `package.json`'s `"ark"` key)                  |
| ------------------------------------------------------------- | -------------------------------------------------------------------- |
| `drizzle-arktype`, which creates Types from tables as it runs | `"precompile": { "dependencies": { "drizzle-arktype": "arktype" } }` |
| t3-env's `presets-arktype`, which defines static Types        | `"precompile": { "dependencies": { "@t3-oss/env-core": "aot" } }`    |

Without it, a build importing `drizzle-arktype` or `presets-arktype` fails, naming the setting. A package that imports arktype itself, like `@hono/arktype-validator`, has to be bundled with your validators, so a server build with Vite fails until `ssr.noExternal` names it. [Troubleshooting](/docs/precompile/troubleshooting) has each message.

A [production build](/docs/precompile/options#prune) keeps `~standard` in a validator a library like Hono's `sValidator` validates with, and leaves out what nothing reads.

---

### Ark Docs Content Docs (Arktype) Objects Index (`ark/docs/content/docs/(arktype)/objects/index.mdx`)

---
title: Objects
description: Define objects, arrays, tuples, dates and class instances, and derive new object types from existing ones.
---

## properties

An object definition can combine required, optional and defaultable keys with index signatures.

### required [#properties-required]

<SyntaxTabs>
	<SyntaxTab string>

```ts
const symbolicKey = Symbol()

const MyObj = type({
	requiredKey: "string",
	// nested definitions don't need their own type call
	[symbolicKey]: {
		nested: "unknown"
	}
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const symbolicKey = Symbol()

const MyObj = type({
	requiredKey: type.string,
	// nested definitions don't need their own type call
	[symbolicKey]: {
		nested: type.unknown
	}
})
```

    </SyntaxTab>

</SyntaxTabs>

### optional [#properties-optional]

<SyntaxTabs>
	<SyntaxTab string>

```ts
const symbolicKey = Symbol()

const MyObj = type({
	"optionalKey?": "number[]",
	[symbolicKey]: "string?"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const symbolicKey = Symbol()

const MyObj = type({
	optionalKey: type.number.array().optional(),
	[symbolicKey]: type.string.optional()
})
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const symbolicKey = Symbol()

const MyObj = type({
	optionalKey: ["number[]", "?"],
	[symbolicKey]: ["string", "?"]
})
```

    </SyntaxTab>

</SyntaxTabs>

<Callout type="info" title="Key or value syntax?">

Prefer the key syntax, `"key?"`. It mirrors TypeScript and reads as what it is: a constraint on whether the key is present, not on its value.

Put `?` on the value when the key is a symbol, when you want go-to-definition and JSDoc on an unquoted key, or when you'd rather not quote keys.

</Callout>

<Callout type="warn" title="An optional key doesn't allow undefined">

ArkType checks optional keys the way TypeScript does with [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes): a missing key is valid, but a key set to `undefined` must allow `undefined`.

```ts
const MyObj = type({
	"key?": "number"
})

// {}
MyObj({})

// ArkErrors: key must be a number
MyObj({ key: undefined })
```

To allow it, add `undefined` to the value: `"key?": "number | undefined"`. You can also set [`exactOptionalPropertyTypes`](/docs/configuration#exactoptionalpropertytypes) to `false` globally.

</Callout>

### defaultable [#properties-defaultable]

A defaultable key is optional in the input. When it is missing, the output has its default.

<SyntaxTabs>
	<SyntaxTab string>

```ts
const MyObj = type({
	defaultableKey: "boolean = false"
})

// { defaultableKey: false }
MyObj({})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const MyObj = type({
	defaultableKey: type.boolean.default(false)
})

// { defaultableKey: false }
MyObj({})
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const MyObj = type({
	defaultableKey: ["boolean", "=", false]
})

// { defaultableKey: false }
MyObj({})
```

    </SyntaxTab>

</SyntaxTabs>

`= []` and `= {}` give each output its own new array or object, so mutating one never changes another:

```ts
const MyObj = type({
	values: "string[] = []",
	meta: "object = {}"
})
```

For any other object, default to a function that returns it, e.g. `type.Date.default(() => new Date())`.

<Callout type="warn" title="Optional and default only work in objects and tuples">

`number.optional()` and `number.default(0)` don't return a `Type`. They return the tuple definitions `[Type<number>, "?"]` and `[Type<number>, "=", 0]`, which are only valid as a property or a tuple element. `type("string?")` throws a `ParseError`.

For a `Type` that accepts `undefined`, use a union like `type("string | undefined")`. To replace `undefined` with a value, add a morph:

```ts
const FallbackString = type("string | undefined").pipe(v => v ?? "")
```

</Callout>

### index [#properties-index]

An index signature constrains every key that matches it:

```ts
const Scores = type({
	"[string]": "number"
})
```

The key can be any string or symbol type, like `symbol`, `string | symbol`, a keyword like `string.uuid` or a regex literal:

```ts
const DataAttributes = type({
	"[/^data-/]": "string"
})

// ArkErrors: ["data-id"] must be a string
DataAttributes({ "data-id": 1 })
```

A union of literal keys becomes those named keys, so `"['a' | 'b']": "number"` is `{ a: number, b: number }`.

`Record` is available as a [generic keyword](/docs/generics#keywords), e.g. `type("Record<string, number>")` or `type.Record("string", "number")`.

### undeclared [#properties-undeclared]

By default, ArkType allows keys you didn't declare, like TypeScript does. That lets you validate an object you already have without copying it, and skipping the check for extra keys is faster.

To reject or delete undeclared keys, set `"+"` in the object, or [configure](/docs/configuration#onundeclaredkey) a different default for every object:

<SyntaxTabs>
	<SyntaxTab string>

```ts
// fail if any string key other than "onlyAllowedKey" is present
const MyClosedObject = type({
	"+": "reject",
	onlyAllowedKey: "string"
})

// delete every key other than "onlyPreservedKey"
const MyStrippedObject = type({
	"+": "delete",
	onlyPreservedKey: "string"
})

// allow and keep undeclared keys (the default)
const MyOpenObject = type({
	"+": "ignore",
	nonexclusiveKey: "number"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// fail if any string key other than "onlyAllowedKey" is present
const MyClosedObject = type({
	onlyAllowedKey: "string"
}).onUndeclaredKey("reject")

// delete every key other than "onlyPreservedKey"
const MyStrippedObject = type({
	onlyPreservedKey: "string"
}).onUndeclaredKey("delete")

// allow and keep undeclared keys (the default)
const MyOpenObject = type({
	nonexclusiveKey: "number"
}).onUndeclaredKey("ignore")
```

    </SyntaxTab>

</SyntaxTabs>

`"ignore"` only matters if you configured a different default.

A rejected key is an error with the code `undeclared`:

```ts
const MyClosedObject = type({
	"+": "reject",
	onlyAllowedKey: "string"
})

// ArkErrors: extraKey must be removed
MyClosedObject({ onlyAllowedKey: "ok", extraKey: 1 })
```

Both act on string keys: `"reject"` checks only an object's string keys, and `"delete"` builds a new object holding only its declared keys. So an undeclared symbol key passes `"reject"` and is dropped by `"delete"`, and reject types that differ only by a symbol key overlap, so a union of them with a morph is indeterminate.

`"delete"`'s output lists the declared keys in the order the definition declares them, as Zod does, then any keys matching an index signature in the input's order.

`.onDeepUndeclaredKey()` applies the same behavior to every nested object:

```ts
const MyDeeplyStrippedObject = type({
	preserved: "string",
	nested: {
		preserved: "string"
	}
}).onDeepUndeclaredKey("delete")

// { nested: { preserved: "b" }, preserved: "a" }
MyDeeplyStrippedObject({
	preserved: "a",
	extra: 1,
	nested: { preserved: "b", extra: 2 }
})
```

<Callout type="info" title="Prefer in-object syntax where possible">

`.onUndeclaredKey()` and `.configure()` rebuild the whole type they're called on, so creating a type with them is slower than writing `"+"` in the object. Validation is equally fast either way. Methods like `.or()` and `.pipe()` reference the original type rather than rebuilding it, so they have no such cost.

</Callout>

<AnchorAliases properties-merge spread properties-spread />
### merge

Merging adds properties to an object or replaces existing ones, like JavaScript's [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). Write it as a `"..."` key in the object, `.merge()` or the `Merge` generic:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const User = type({ isAdmin: "false", name: "string" })

// Type<{ name: string; isAdmin: true; permissions: string[] }>
const Admin = type({
	"...": User,
	isAdmin: "true",
	permissions: "string[]"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const User = type({ isAdmin: "false", name: "string" })

// Type<{ name: string; isAdmin: true; permissions: string[] }>
const Admin = User.merge({
	isAdmin: "true",
	permissions: "string[]"
})
```

    </SyntaxTab>

    <SyntaxTab generic>

```ts
const types = type.module({
	User: { isAdmin: "false", name: "string" },
	AdminProps: { isAdmin: "true", permissions: "string[]" },
	// { name: string; isAdmin: true; permissions: string[] }
	Admin: "Merge<User, AdminProps>"
})
```

    </SyntaxTab>

</SyntaxTabs>

A key in both objects takes its value from the merged object. An [intersection](/docs/expressions#intersection) would instead intersect the two values, and `false & true` would throw a `ParseError`. When the keys don't overlap, the two give the same type, but merging is less work to compute, both when the type is created and in your editor, so prefer it for combining properties.

Like the other [structural transformations](/docs/objects#properties-structural), `merge` builds a new object from the properties, so a root narrow or metadata is not carried over.

<AnchorAliases merge-n-ary />
#### n-ary

`type.merge` merges any number of objects, each overriding the ones before it:

```ts
// Type<{ b: number; a?: 1 }>
const Merged = type.merge({ a: "string" }, { b: "number" }, { "a?": "1" })
```

### escapes [#properties-escapes]

Escape a key's `?`, the `[` of a key in brackets, or a key that is exactly `+`, `...` or `@`, with a backslash to use it literally:

```ts
// Type<{ "isAdmin?": boolean; "+": string; "[id]"?: string }>
const Escaped = type({
	"isAdmin\\?": "boolean",
	"\\+": "string",
	"\\[id]?": "string"
})

// ArkErrors: ["isAdmin?"] must be boolean (was missing)
Escaped({ "+": "x" })
```

An index signature can't be optional, so a key like `"[id]?"` throws a `ParseError` unless its `[` is escaped.

### keyof [#properties-keyof]

Like in TypeScript, `keyof` extracts an object's keys as a union:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const types = type.module({
	UsedCar: {
		originallyPurchased: "string.date",
		remainingWheels: "number"
	},
	// "originallyPurchased" | "remainingWheels"
	UsedCarKey: "keyof UsedCar"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const UsedCar = type({
	originallyPurchased: "string.date",
	remainingWheels: "number"
})

// Type<"originallyPurchased" | "remainingWheels">
const UsedCarKey = UsedCar.keyof()
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const UsedCar = type({
	originallyPurchased: "string.date",
	remainingWheels: "number"
})

// Type<"originallyPurchased" | "remainingWheels">
const UsedCarKey = type(["keyof", UsedCar])
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const UsedCar = type({
	originallyPurchased: "string.date",
	remainingWheels: "number"
})

// Type<"originallyPurchased" | "remainingWheels">
const UsedCarKey = type("keyof", UsedCar)
```

    </SyntaxTab>

</SyntaxTabs>

Also like in TypeScript, a `[string]` index signature absorbs the named keys, so `keyof` is `string`:

```ts
const RecordWithSpecialKeys = type({
	"[string]": "unknown",
	verySpecialKey: "number"
})

// true
RecordWithSpecialKeys.keyof().equals("string")
```

<Callout type="warn" title="ArkType's keyof never includes number">

TypeScript's `keyof` can include `number`, but JavaScript has no numeric keys: `{ 4: true }` and `{ "4": true }` are the same object, and `Object.keys` returns `["4"]` for both. ArkType's `keyof` only returns `string` and `symbol` keys, the two kinds of key an object can have.

<details>
	<summary>Why ArkType diverges from TypeScript here</summary>

In a set-based type system, two types that describe the same values need the same representation. TypeScript keeps separate numeric and string representations of the same key, which leads to results like this:

```ts
type Thing1 = {
	[x: string]: unknown
}

// Thing2 describes the same values as Thing1
type Thing2 = Record<string, unknown>

type Key1 = keyof Thing1
//   ^?

type Key2 = keyof Thing2
//   ^?
```

</details>

</Callout>

### get [#properties-get]

Like an indexed access type in TypeScript (`User["name"]`), `get` extracts the type of the value at a key:

```ts
const Manatee = type({
	isFriendly: "true",
	snorf: {
		uses: "string[]"
	}
})

// Type<true>
const IsFriendly = Manatee.get("isFriendly")

// pass more keys to access nested properties
// Type<string[]>
const SnorfUses = Manatee.get("snorf", "uses")
```

The key can also be a union, a literal or an index signature, and the object can be a union with optional keys. The [`get` tests](https://github.com/arktypeio/arktype/blob/main/ark/type/__tests__/get.test.ts) cover each case.

<Callout type="warn" title="Extracting part of a type can be an antipattern">

Before using `get`, `pick` or `omit` on a type you defined, consider defining that part as its own type and referencing it. Composing small types is usually clearer and faster than extracting parts of a large one.

</Callout>

### structural transformations [#properties-structural]

`merge`, `pick`, `omit`, `required`, `partial` and `map` each return a **new object built from the properties** of the `Type` they're called on, rather than referencing that `Type`.

<Callout type="warn" title="Only properties are carried over">

Anything attached to the object itself is dropped: most importantly a root [narrow](/docs/expressions#narrow) or [filter](/docs/expressions#filter), but also [metadata](/docs/configuration#metadata) like `.describe(...)`. Constraints on the properties are kept.

```ts
const User = type({
	name: "string",
	email: "string"
}).narrow(user => user.email.includes("@"))

// the narrow is not a property, so PartialUser doesn't have it
const PartialUser = User.partial()

// { email: "not an email" }
PartialUser({ email: "not an email" })
```

Reapply what you still need to the result:

```ts
const PartialUser = type({
	name: "string",
	email: "string"
})
	.partial()
	.narrow(user => user.email?.includes("@") ?? true)
```

A root [morph](/docs/expressions#pipe) can't be reduced to properties, so transforming a type like `type({ name: "string" }).pipe(user => user)` throws a `ParseError` instead of dropping it.

</Callout>

### pick / omit [#properties-pick-omit]

Keep or remove specific properties:

```ts
const User = type({
	name: "string",
	email: "string.email",
	"age?": "number"
})

// Type<{ name: string; email: string }>
const NameAndEmail = User.pick("name", "email")

// Type<{ name: string; age?: number }>
const WithoutEmail = User.omit("email")
```

In a definition, use the `Pick` and `Omit` [generics](/docs/generics#keywords). Their keys are definitions, so quote each one:

```ts
const types = type.module({
	User: {
		name: "string",
		email: "string.email",
		"age?": "number"
	},
	NameAndEmail: "Pick<User, 'name' | 'email'>",
	WithoutEmail: "Omit<User, 'email'>"
})
```

### required / partial [#properties-required-partial]

Make every named property required or optional:

```ts
const User = type({
	name: "string",
	"email?": "string.email",
	"age?": "number"
})

// Type<{ name: string; email: string; age: number }>
const RequiredUser = User.required()

// Type<{ name?: string; email?: string; age?: number }>
const PartialUser = User.partial()
```

`required` also removes defaults, so a defaulted key becomes a plain required key:

```ts
// Type<{ foo: string }>
const T = type({ foo: "string = 'bar'" }).required()

// ArkErrors: foo must be a string (was missing)
T({})
```

In a definition, use the `Required` and `Partial` [generics](/docs/generics#keywords), e.g. `"Partial<User>"` in a scope.

<Callout type="info" title="Arrays and tuples mirror TypeScript's Required and Partial">

Like the mapped types they're named for, `required` and `partial` apply to an array's or tuple's elements:

```ts
// Type<[string?, number?]>
const PartialPair = type(["string", "number"]).partial()

// Type<[string, number]>
const RequiredPair = type(["string", "number?"]).required()
```

They only change whether an element must be present, never the values it allows. TypeScript also adds `undefined` to variadic elements and index signature values, since it has no way to mark them optional. ArkType doesn't, so `type("string[]").partial()` is still `string[]`.

A postfix element can't follow an optional one, in ArkType or in TypeScript, so `partial` throws a `ParseError` on a tuple like `[string, ...number[], boolean]`.

</Callout>

### readonly [#properties-readonly]

Mark every property as `readonly`. This only affects the inferred type; the output isn't frozen.

```ts
// Type<{ readonly id: number; readonly name: string }>
const Frozen = type({
	id: "number",
	name: "string"
}).readonly()
```

### map [#properties-map]

`map` transforms each property of an object. The function receives a prop with its `key`, `value` (a `Type`) and `kind` (`"required"` or `"optional"`), and returns a `{ key, value }` object, optionally with `kind`:

```ts
const Name = type({
	first: "string",
	last: "string"
})

// Type<{ first: string | null; last: string | null }>
const NullableName = Name.map(prop => ({
	key: prop.key,
	value: prop.value.or("null")
}))
```

Return `[]` to remove a property, or several props to add more than one:

```ts
const User = type({
	name: "string",
	"age?": "number"
})

// Type<{ name: string }>
const NameOnly = User.map(prop => (prop.key === "age" ? [] : prop))
```

### props [#properties-props]

`props` lists an object's properties, with required keys first, then optional keys, each sorted by name:

```ts
const User = type({
	name: "string",
	"age?": "number",
	role: "'admin' | 'user' = 'user'"
})

for (const prop of User.props) {
	console.log(prop.kind) // "required", "optional", "optional"
	console.log(prop.key) // "name", "age", "role"
	console.log(prop.value.expression) // "string", "number", '"admin" | "user"'
	if ("default" in prop) console.log(prop.default) // "user"
}
```

## arrays

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Arrays = type({
	key: "string[]"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Arrays = type({
	key: type.string.array()
})
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const Arrays = type({
	key: ["string", "[]"]
})
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
const Arrays = type({
	key: type("string", "[]")
})
```

    </SyntaxTab>

</SyntaxTabs>

### lengths [#arrays-lengths]

Constrain an array's length with `>`, `>=`, `<`, `<=`, `==` or `!=`:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Bounded = type({
	nonEmpty: "string[] > 0",
	atMost5: "boolean[] <= 5",
	pair: "number[] == 2"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Bounded = type({
	nonEmpty: type.string.array().moreThanLength(0),
	atMost5: type.boolean.array().atMostLength(5),
	pair: type.number.array().exactlyLength(2)
})
```

    </SyntaxTab>

</SyntaxTabs>

A range sets both bounds at once, each inclusive or exclusive:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Tags = type("0 < string[] <= 10")

// ArkErrors: must be non-empty
Tags([])
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Tags = type.string.array().moreThanLength(0).atMostLength(10)

// ArkErrors: must be non-empty
Tags([])
```

    </SyntaxTab>

</SyntaxTabs>

## tuples

Like objects, tuples are structures whose values are nested definitions. Like TypeScript, ArkType supports prefix, defaultable, optional, variadic and postfix elements, with the same rules for combining them.

### prefix [#tuples-prefix]

<SyntaxTabs>
	<SyntaxTab string>

```ts
const MyTuple = type([
	"string",
	// object definitions can be nested in tuples, and vice versa
	{
		coordinates: ["number", "number"]
	}
])
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const MyTuple = type([
	type.string,
	// object definitions can be nested in tuples, and vice versa
	{
		coordinates: [type.number, type.number]
	}
])
```

    </SyntaxTab>

</SyntaxTabs>

### defaultable [#tuples-defaultable]

A defaultable element is optional in the input. When it is missing, the output has its default.

Defaultable elements follow the prefix elements and come before any optional elements. Like optional elements, they can't be combined with postfix elements.

<SyntaxTabs>
	<SyntaxTab string>

```ts
const MyTuple = type(["string", "boolean = false", "number = 0"])

// ["a", false, 0]
MyTuple(["a"])
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const MyTuple = type([
	type.string,
	type.boolean.default(false),
	type.number.default(0)
])

// ["a", false, 0]
MyTuple(["a"])
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const MyTuple = type(["string", ["boolean", "=", false], ["number", "=", 0]])

// ["a", false, 0]
MyTuple(["a"])
```

    </SyntaxTab>

</SyntaxTabs>

### optional [#tuples-optional]

An optional element may be absent from the input and has no default.

Optional elements follow the prefix and defaultable elements, and come before a variadic element or the end of the tuple. Like in TypeScript, they can't be combined with postfix elements.

<SyntaxTabs>
	<SyntaxTab string>

```ts
const MyTuple = type(["string", "boolean?", "number?"])

// ["a"]
MyTuple(["a"])
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const MyTuple = type([
	type.string,
	type.boolean.optional(),
	type.number.optional()
])

// ["a"]
MyTuple(["a"])
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
const MyTuple = type(["string", ["boolean", "?"], ["number", "?"]])

// ["a"]
MyTuple(["a"])
```

    </SyntaxTab>

</SyntaxTabs>

### variadic [#tuples-variadic]

Like in TypeScript, a variadic element allows zero or more consecutive values of a type. A tuple can have at most one. Write it as `"..."` followed by an array:

<SyntaxTabs>
	<SyntaxTab string>

```ts
// a string followed by zero or more numbers
const MyTuple = type(["string", "...", "number[]"])
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// a string followed by zero or more numbers
const MyTuple = type([type.string, "...", type.number.array()])
```

    </SyntaxTab>

</SyntaxTabs>

### postfix [#tuples-postfix]

Postfix elements are required elements after a variadic element. They can't be combined with optional or defaultable elements.

<SyntaxTabs>
	<SyntaxTab string>

```ts
// zero or more numbers followed by a boolean, then a string
const MyTuple = type(["...", "number[]", "boolean", "string"])
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// zero or more numbers followed by a boolean, then a string
const MyTuple = type(["...", type.number.array(), type.boolean, type.string])
```

    </SyntaxTab>

</SyntaxTabs>

## dates

`Date` allows a valid `Date` instance. An invalid date, like `new Date("x")`, is rejected:

```ts
// ArkErrors: must be a Date
type.Date(new Date("x"))
```

To accept invalid dates everywhere, configure [`dateAllowsInvalid`](/docs/configuration#dateallowsinvalid).

### literals [#dates-literals]

A date literal, `d'...'` or `d"..."`, is a `Date` with an exact value. They're mostly useful as [range](/docs/objects#dates-ranges) bounds.

```ts
const Literals = type({
	singleQuoted: "d'1970-01-01'",
	doubleQuoted: 'd"1970-01-01"'
})
```

A literal, like a string passed as a date limit, must be the same instant on every machine, so it can be an ISO date like `2025-01-01` (which is UTC), an ISO date-time with `Z` or an offset like `2025-01-01T12:00+01:00`, or a number of epoch milliseconds. Any other literal, like `d'notadate'` or `d'2025-01-01T12:00'`, is a `ParseError`.

### ranges [#dates-ranges]

Constrain a `Date` with `>`, `>=`, `<`, `<=`, `==` or `!=`. A bound is either a [date literal](/docs/objects#dates-literals) or a number of milliseconds since the Unix epoch.

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Bounded = type({
	inThePast: `Date < ${Date.now()}`,
	from2000: "Date >= d'2000-01-01'",
	before2100: "Date < d'2100-01-01'"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Bounded = type({
	inThePast: type.Date.earlierThan(Date.now()),
	from2000: type.Date.atOrAfter("2000-01-01"),
	before2100: type.Date.earlierThan("2100-01-01")
})
```

    </SyntaxTab>

</SyntaxTabs>

The fluent methods are `laterThan`, `atOrAfter`, `earlierThan` and `atOrBefore`.

A range sets both bounds at once, each inclusive or exclusive:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const tenYearsAgo = new Date().setFullYear(new Date().getFullYear() - 10)

const Recent = type(`${tenYearsAgo} <= Date < ${Date.now()}`)
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const tenYearsAgo = new Date().setFullYear(new Date().getFullYear() - 10)

const Recent = type.Date.atOrAfter(tenYearsAgo).earlierThan(Date.now())
```

    </SyntaxTab>

</SyntaxTabs>

Descriptions and error messages write dates in UTC. A date at UTC midnight is written as its calendar date:

```ts
// "a Date and January 1, 2023 or later"
type("Date >= d'2023-01-01'").description

// "a Date and January 1, 2023, 2:30 PM UTC or later"
type("Date >= d'2023-01-01T14:30Z'").description
```

## instanceof

Most built-in classes like `Array`, `Date` and `Map` are [keywords](/docs/keywords#instanceof). Use `instanceof` for your own classes:

<SyntaxTabs>
	<SyntaxTab fluent>

```ts
class MyClass {}

const Instance = type.instanceOf(MyClass)
```

    </SyntaxTab>

    <SyntaxTab tuple>

```ts
class MyClass {}

const Instance = type(["instanceof", MyClass])
```

    </SyntaxTab>

    <SyntaxTab args>

```ts
class MyClass {}

const Instance = type("instanceof", MyClass)
```

    </SyntaxTab>

</SyntaxTabs>

<Callout type="info" title="Array is the only constructor that works across realms">

Constructors are compared by identity, so a value created in another realm, like an `<iframe>` or a `node:vm` context, is not an instance of the constructor in yours. `Array` is checked with `Array.isArray`, so it also matches arrays from another realm.

</Callout>

### keywords [#instanceof-keywords]

The [keywords](/docs/keywords#instanceof) page lists every built-in class keyword, along with the subtypes of [Array](/docs/keywords#array) and [FormData](/docs/keywords#formdata).

Keywords for web platform classes, like `Blob`, `File`, `URL`, `FormData`, `Headers`, `Request` and `Response`, throw when used in a runtime that doesn't define that class, e.g. `'Blob' is unresolvable`.

---

### Ark Docs Content Docs (Arktype) Primitives Index (`ark/docs/content/docs/(arktype)/primitives/index.mdx`)

---
title: Primitives
description: Define strings, numbers, bigints, symbols, booleans, null and undefined, with literals, patterns, lengths, ranges and divisors.
---

## string

### keywords [#string-keywords]

Reference a keyword anywhere a definition is expected:

```ts
const User = type({
	email: "string.email",
	ids: "string.uuid.v4[]"
})
```

<StringKeywordTable />

Every keyword, including those for other types, is listed on the [keywords](/docs/keywords) page.

### literals [#string-literals]

Quote a string inside a definition to allow exactly that string. Single and double quotes are equivalent:

```ts
const Literals = type({
	singleQuoted: "'typescript'",
	doubleQuoted: '"arktype"'
})
```

### patterns [#string-patterns]

A regex literal requires the string to match it. Like a `RegExp`, it is unanchored unless you anchor it with `^` and `$`.

<SyntaxTabs>
	<SyntaxTab string>

```ts
const AToZ = type("/^a.*z$/")

// ArkErrors: must be matched by ^a.*z$
AToZ("abc")
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const AToZ = type.string.matching(/^a.*z$/)

// ArkErrors: must be matched by ^a.*z$
AToZ("abc")
```

    </SyntaxTab>

</SyntaxTabs>

A `RegExp` works as a definition too, e.g. `type({ code: /^a.*z$/ })`.

Regex literals are typed with [ArkRegex](/docs/regex), so a pattern that constrains the string's shape narrows the inferred type:

```ts
// Type<string>
const Hex = type("/^[0-9a-fA-F]+$/")

// Type<`${number}.${number}.${number}`>
const Semver = type("/^(\\d+)\\.(\\d+)\\.(\\d+)$/")
```

#### e(x)ec mode

Prefix a regex literal with `x` to transform the string into the result of `RegExp.prototype.exec`. The output is the match, not the string, and its capture groups are typed:

```ts
const User = type({
	birthday: "x/^(?<month>\\d{2})-(?<day>\\d{2})-(?<year>\\d{4})$/"
})

const data = User.assert({ birthday: "05-21-1993" })

data.birthday.groups.month // "05"
data.birthday.groups.year // "1993"
```

### lengths [#string-lengths]

Constrain a string's length with `>`, `>=`, `<`, `<=`, `==` or `!=`:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Bounded = type({
	nonEmpty: "string > 0",
	atMost10: "string <= 10",
	exactly5: "string == 5"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Bounded = type({
	nonEmpty: type.string.moreThanLength(0),
	atMost10: type.string.atMostLength(10),
	exactly5: type.string.exactlyLength(5)
})
```

    </SyntaxTab>

</SyntaxTabs>

A range sets both bounds at once, each inclusive or exclusive:

<SyntaxTabs>
	<SyntaxTab string>

```ts
// 4 to 6 digits
const Pin = type("4 <= string.digits <= 6")

// ArkErrors: must be at least length 4
Pin("123")
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
// 4 to 6 digits
const Pin = type.keywords.string.digits.atLeastLength(4).atMostLength(6)

// ArkErrors: must be at least length 4
Pin("123")
```

    </SyntaxTab>

</SyntaxTabs>

## number

`number` rejects `NaN`, `Infinity` and `-Infinity`. Allow them in one type with the `number.NaN`, `number.Infinity` and `number.NegativeInfinity` keywords:

```ts
const MaybeInfinite = type("number | number.Infinity | number.NegativeInfinity")
```

To allow them everywhere, configure [`numberAllowsNaN`](/docs/configuration#numberallowsnan) or [`numberAllowsInfinity`](/docs/configuration#numberallowsinfinity).

### keywords [#number-keywords]

```ts
const User = type({
	createdAt: "number.epoch",
	age: "number.integer >= 0"
})
```

<NumberKeywordTable />

### literals [#number-literals]

A number in a definition allows exactly that number:

```ts
const Literals = type({
	number: "1337"
})
```

### ranges [#number-ranges]

Constrain a number with `>`, `>=`, `<` or `<=`:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Bounded = type({
	positive: "number > 0",
	atMost5: "number <= 5"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Bounded = type({
	positive: type.number.moreThan(0),
	atMost5: type.number.atMost(5)
})
```

    </SyntaxTab>

</SyntaxTabs>

A range sets both bounds at once, each inclusive or exclusive:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Percentage = type("0 <= number <= 100")

// ArkErrors: must be at most 100
Percentage(101)
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Percentage = type.number.atLeast(0).atMost(100)

// ArkErrors: must be at most 100
Percentage(101)
```

    </SyntaxTab>

</SyntaxTabs>

`!=` excludes one value:

```ts
const NonZero = type("number != 0")

// ArkErrors: must be other than 0
NonZero(0)
```

### divisors [#number-divisors]

Constrain a number to a multiple of an integer with `%`:

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Even = type("number % 2")

// ArkErrors: must be even
Even(3)
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Even = type.number.divisibleBy(2)

// ArkErrors: must be even
Even(3)
```

    </SyntaxTab>

</SyntaxTabs>

## bigint

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Bigints = type({
	foo: "bigint"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Bigints = type({
	foo: type.bigint
})
```

    </SyntaxTab>

</SyntaxTabs>

### literals [#bigint-literals]

Add the suffix `n` to a [number literal](/docs/primitives#number-literals) to allow exactly that `bigint`:

```ts
const Literals = type({
	bigint: "1337n"
})
```

A [unit expression](/docs/expressions#unit) like `type.unit(1337n)` does the same.

## symbol

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Symbols = type({
	key: "symbol"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Symbols = type({
	key: type.symbol
})
```

    </SyntaxTab>

</SyntaxTabs>

To allow one specific symbol, use a [unit expression](/docs/expressions#unit).

Symbol keys need no special syntax, e.g. `{ [mySymbol]: "string" }`. See [properties](/docs/objects#properties) to make them optional or defaultable.

## boolean

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Booleans = type({
	key: "boolean"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Booleans = type({
	key: type.boolean
})
```

    </SyntaxTab>

</SyntaxTabs>

### literals [#boolean-literals]

<SyntaxTabs>
	<SyntaxTab string>

```ts
const Booleans = type({
	a: "true",
	b: "false",
	// equivalent to "boolean"
	c: "true | false"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const Booleans = type({
	a: type.true,
	b: type.false,
	// equivalent to type.boolean
	c: type.true.or(type.false)
})
```

    </SyntaxTab>

</SyntaxTabs>

## null

`"null"` allows exactly `null`, usually in a [union](/docs/expressions#union):

<SyntaxTabs>
	<SyntaxTab string>

```ts
const MyObj = type({
	foo: "number | null"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const MyObj = type({
	foo: type.number.or(type.null)
})
```

    </SyntaxTab>

</SyntaxTabs>

## undefined

`"undefined"` allows exactly `undefined`, usually in a [union](/docs/expressions#union):

<SyntaxTabs>
	<SyntaxTab string>

```ts
const MyObj = type({
	requiredKey: "number | undefined",
	"optionalKey?": "number | undefined"
})
```

    </SyntaxTab>

    <SyntaxTab fluent>

```ts
const MyObj = type({
	requiredKey: type.number.or(type.undefined),
	optionalKey: type.number.or(type.undefined).optional()
})
```

    </SyntaxTab>

</SyntaxTabs>

<Callout type="warn" title="Allowing undefined does not make a key optional">

Like in TypeScript, a required key that allows `undefined` must still be present:

```ts
const MyObj = type({
	key: "number | undefined"
})

// { key: undefined }
MyObj({ key: undefined })

// ArkErrors: key must be a number or undefined (was missing)
MyObj({})
```

</Callout>

---

### Ark Docs Content Docs (Arktype) Scopes Index (`ark/docs/content/docs/(arktype)/scopes/index.mdx`)

---
title: Scopes
description: Define aliases that reference each other, then use them in definitions or export them as a module of Types.
---

<AnchorAliases intro />

A scope is a set of named definitions, called aliases, that can reference each other the same way they reference keywords like `string`. The `type` function you import from `arktype` is a method of ArkType's default scope.

## Defining a scope

Pass `scope` an object mapping alias names to definitions:

```ts
import { scope } from "arktype"

const $ = scope({
	Id: "string",
	User: { id: "Id", friends: "Id[]" },
	UsersById: { "[Id]": "User" }
})
```

Aliases are autocompleted and validated like built-in keywords. Write definitions inside a scope directly: wrapping one in `type(...)` fails, because `type` only knows built-in keywords (see [thunks](#thunks)).

`$.type` parses a definition that can reference the scope's aliases. Types created this way keep their scope, so chained methods can reference the aliases too:

```ts
const $ = scope({
	Id: "string",
	User: { id: "Id", friends: "Id[]" },
	UsersById: { "[Id]": "User" }
})
// ---cut---
const Group = $.type({ name: "string", members: "User[]" })

const OwnedGroup = Group.and({ ownerId: "Id" })
```

`$.match`, `$.declare`, `$.generic` and `$.fn` work like their counterparts on `type`, but also resolve the scope's aliases.

## Modules

`.export()` turns a scope into a `Module`, an object mapping each alias to its `Type`:

```ts
const $ = scope({
	Id: "string",
	User: { id: "Id", friends: "Id[]" },
	UsersById: { "[Id]": "User" }
})
// ---cut---
const types = $.export()

// ArkErrors: friends[1] must be a string
types.User({ id: "99", friends: ["7", 8, "9"] })
```

To get a single `Type`, use `$.resolve("User")`.

`type.module` defines a scope and exports it in one call:

```ts
const types = type.module({
	Id: "string",
	User: { id: "Id", friends: "Id[]" }
})
```

A `Module` can be spread into another scope to include all of its aliases. Pass names to `.export()` to include only those:

```ts
const $ = scope({
	Id: "string",
	User: { id: "Id", friends: "Id[]" },
	UsersById: { "[Id]": "User" }
})
// ---cut---
const numbers = scope({ Three: "3", Sixty: "60", No: "'no'" })

const superScope = scope({
	...$.export(),
	...numbers.export("Three", "Sixty"),
	Saiyan: { powerLevel: "number > 9000" }
})
```

## Cyclic types

Aliases can reference themselves and each other:

```ts
const types = scope({
	Package: {
		name: "string",
		"dependencies?": "Package[]",
		"contributors?": "Contributor[]"
	},
	Contributor: {
		email: "string.email",
		"packages?": "Package[]"
	}
}).export()
```

Cyclic types are inferred to any depth, and they validate cyclic data:

```ts
const types = scope({
	Package: {
		name: "string",
		"dependencies?": "Package[]",
		"contributors?": "Contributor[]"
	},
	Contributor: {
		email: "string.email",
		"packages?": "Package[]"
	}
}).export()
// ---cut---
type Package = typeof types.Package.infer

const packageData: Package = {
	name: "arktype",
	dependencies: [{ name: "typescript" }],
	contributors: [{ email: "david@sharktypeio" }]
}

// arktype now depends on itself
packageData.dependencies![0].dependencies = [packageData]

// ArkErrors: contributors[0].email must be an email address
types.Package(packageData)
```

A cycle must pass through an object, array or morph. An alias that resolves to itself without one, like `a` in `scope({ a: "a | string" })`, is a type error and throws a `ParseError`.

For a single recursive `Type`, you don't need a scope: use the [`this`](/docs/expressions#this) keyword.

<Callout type="warn" title="Cyclic types may display as any">

TypeScript shows an anonymous cycle as `...`, or as `any` if `noErrorTruncation` is enabled. Either way, the type itself is accurate: you get completions, and accessing a property that doesn't exist is an error.

</Callout>

## Visibility

Aliases prefixed with `#` are private. They can be referenced in the scope, but are not exported:

```ts
const shapes = scope({
	"#BaseShape": { perimeter: "number", area: "number" },
	// reference private aliases without the "#"
	Ellipse: { "...": "BaseShape", radii: ["number", "number"] },
	Rectangle: { "...": "BaseShape", width: "number", height: "number" }
})

// shapes.type can still reference private aliases
const PartialShape = shapes.type("Partial<BaseShape>")

const shapeModule = shapes.export()
Object.keys(shapeModule) // ["Ellipse", "Rectangle"]
```

### `import()`

`.import()` is like `.export()`, but makes every alias private. Spread it into a scope to use another scope's aliases without re-exporting them:

```ts
const utilities = scope({
	"WithId<o extends object>": { "...": "o", id: "string" }
})

const userModule = type.module({
	...utilities.import(),
	Payload: { name: "string", age: "number" },
	Db: "WithId<Payload>"
})

Object.keys(userModule) // ["Payload", "Db"]
```

## Submodules

Keywords like `string.email` are grouped into submodules. To group your own aliases, assign a `Module` to an alias and reference its members with a `.`:

```ts
const ids = type.module({ User: "string", Order: "number" })

const $ = scope({
	Id: ids,
	Customer: { id: "Id.User", orderIds: "Id.Order[]" }
})
```

Submodules are parsed bottom-up: the root scope can reference a submodule's aliases, but a submodule can't reference the root scope's aliases.

### Nested

Submodules can be nested to any depth:

```ts
const ids = type.module({ User: "string", Order: "number" })

const $ = scope({
	Id: ids,
	Customer: { id: "Id.User", orderIds: "Id.Order[]" }
})
// ---cut---
const store = scope({ Store: $.export() })

const OrderIds = store.type("Store.Id.Order[]")
```

### Rooted

A submodule can't be referenced as a `Type` itself unless it has an alias named `root`, the way `string` is both a keyword and the prefix of `string.email`:

```ts
const userModule = type.module({
	root: { name: "string" },
	// subaliases can reference root like any other alias
	Admin: { "...": "root", isAdmin: "true" },
	Saiyan: { "...": "root", powerLevel: "number > 9000" }
})

const types = type.module({
	User: userModule,
	// User refers to the root alias
	Group: "User[]",
	// or prefixes its subaliases
	ElevatedUser: "User.Admin | User.Saiyan"
})
```

## Thunks

A common mistake is wrapping a scoped definition in `type`:

```ts
// @errors: 2322
const $ = scope({
	Id: "string",
	User: type({
		name: "string",
		id: "Id"
	})
})
```

`Id` exists in the scope, but `type` only knows built-in keywords. Here the wrapper is redundant, so remove it:

```ts
const $ = scope({
	Id: "string",
	User: {
		name: "string",
		id: "Id"
	}
})
```

To use fluent methods like `.pipe` on a scoped definition, define it as a thunk: a function that calls the `type` method of the scope you're defining.

```ts
const $ = scope({
	Id: "string",
	TrimmedId: () => $.type("Id").pipe(s => s.trim())
})

const types = $.export()

types.TrimmedId("  42 ") // "42"
```

A thunk can't pass a callback that receives the data, like `.narrow`'s, to a Type that references the alias the thunk defines. TypeScript would read the callback's parameter from that alias, which is still being inferred from the thunk, and reports the thunk as implicitly `any`. Write the narrow as a tuple expression instead:

```ts
const $ = scope({
	File: { name: "string" },
	Directory: {
		name: "string",
		children: [
			"(File | Directory)[]",
			":",
			children => new Set(children.map(c => c.name)).size === children.length
		]
	}
})
```

## Configuration

`scope` takes a config as its second argument. It applies to every `Type` parsed in the scope:

```ts
const $ = scope({ Even: "number % 2" }, { divisor: { expected: "even" } })

// ArkErrors: must be even
$.export().Even(3)
```

It accepts the same options as [global configuration](/docs/configuration), except these, which can only be configured globally: `onUndeclaredKey`, `numberAllowsNaN`, `numberAllowsInfinity`, `dateAllowsInvalid`, `keywords` and `locale`.

---

### Ark Docs Content Docs (Arktype) Type Api Index (`ark/docs/content/docs/(arktype)/type-api/index.mdx`)

---
title: Type API
description: Every member of a Type and of the type function.
---

Every `Type` has the members below. Types of objects, strings, numbers, arrays and Dates add the ones under [Objects](#objects) and [Constraints](#constraints).

## Validation

A Type is a function. Call it with any data to get the validated output or [`ArkErrors`](/docs/errors):

```ts
const User = type({ name: "string" })

const out = User({ name: 5 })

if (out instanceof type.errors) {
	// name must be a string
	console.error(out.summary)
} else {
	console.log(out.name)
}
```

`allows` checks only the input side of a morph, so a value can be allowed and still fail when the Type is called. See [Validation](/docs/validation) for more.

<ApiTable group="Validation" />

## Inference

<ApiTable group="Inference" />

## Metadata

<ApiTable group="Metadata" />

## Composition

<ApiTable group="Composition" />

## Narrows and morphs

<AnchorAliases in--out />

<ApiTable group="Morphs" />

### pipe.try

Like `pipe`, but a morph that throws adds an error instead of throwing:

```ts
const ParseJson = type("string").pipe.try(s => JSON.parse(s))

ParseJson('{"a": 1}') // { a: 1 }
// ArkErrors: must be valid according to an anonymous predicate (SyntaxError: ...)
ParseJson("{")
```

## Comparison

<AnchorAliases extract--exclude />

<ApiTable group="Comparison" />

### distribute

Map each branch of a union, and optionally reduce the results. A Type that isn't a union is a single branch. This method is experimental.

```ts
const T = type("string | number | bigint")

T.distribute(branch => branch.expression) // ["bigint", "number", "string"]

T.distribute(
	branch => branch.expression,
	expressions => expressions.join(" or ")
) // "bigint or number or string"
```

## Objects

These are available on a Type whose output is an object. See [Objects](/docs/objects#properties-structural) for how each one handles arrays, index signatures and defaults.

<ApiTable group="Objects" />

### readonly

Mark every property `readonly` in the inferred type. Validation is unchanged.

```ts
// Type<{ readonly id: number }>
const Frozen = type({ id: "number" }).readonly()
```

### keyof

A Type of this object's keys.

```ts
// Type<"id" | "name">
const Key = type({ id: "number", name: "string" }).keyof()
```

## Constraints

Each method adds a constraint you could also write in a [string definition](/docs/intro/adding-constraints), and returns a Type of the same kind. A Date bound can be a `Date`, a number of milliseconds or a string `new Date()` accepts.

| Method           | Available on  | Constraint                                          |
| ---------------- | ------------- | --------------------------------------------------- |
| `matching`       | string        | matches a [regex](/docs/primitives#string-patterns) |
| `atLeastLength`  | string, array | length `>= n`                                       |
| `atMostLength`   | string, array | length `<= n`                                       |
| `moreThanLength` | string, array | length `> n`                                        |
| `lessThanLength` | string, array | length `< n`                                        |
| `exactlyLength`  | string, array | length `== n`                                       |
| `atLeast`        | number        | `>= n`                                              |
| `atMost`         | number        | `<= n`                                              |
| `moreThan`       | number        | `> n`                                               |
| `lessThan`       | number        | `< n`                                               |
| `divisibleBy`    | number        | `% n`                                               |
| `atOrAfter`      | Date          | `>= date`                                           |
| `atOrBefore`     | Date          | `<= date`                                           |
| `laterThan`      | Date          | `> date`                                            |
| `earlierThan`    | Date          | `< date`                                            |

```ts
const Username = type.string.matching("^[a-z]+$").atMostLength(16)

// ArkErrors: must be matched by ^[a-z]+$
Username("ArkType")

// Type<`a${string}z`>, inferred from the pattern
const AToZ = type.string.matching("^a.*z$")

const Even = type.number.divisibleBy(2)

// ArkErrors: must be even
Even(3)
```

## Serialization

[To JSON Schema](/docs/json-schema/to-json-schema) covers `toJsonSchema()` and `~standard.jsonSchema`: their options, what they can't represent, and the fallbacks. [Standard Schema](/docs/standard-schema) covers `~standard.validate`.

<ApiTable group="Serialization" />

## Introspection

<ApiTable group="Introspection" />

### internal

The node from `@ark/schema` that a Type is built from. Its API is not semver-stable. See [Nodes](/docs/internals/nodes).

```ts
type("string").internal.kind // "domain"
```

## Members of type

The `type` function has members of its own. Each returns a `Type` unless noted.

| Member             | What it does                                                          |
| ------------------ | --------------------------------------------------------------------- |
| `type.unit`        | a Type of exactly one value                                           |
| `type.enumerated`  | a Type of any of the values passed                                    |
| `type.valueOf`     | a Type of an object's values, e.g. a TypeScript `enum`                |
| `type.instanceOf`  | a Type of instances of a class                                        |
| `type.or`          | a union of every definition passed                                    |
| `type.and`         | an intersection of every definition passed                            |
| `type.merge`       | object definitions merged, later keys winning                         |
| `type.pipe`        | a pipe through each morph or Type passed                              |
| `type.fn`          | a [validated function](/docs/expressions#fn)                          |
| `type.match`       | a [matcher](/docs/match)                                              |
| `type.generic`     | a [generic](/docs/generics)                                           |
| `type.declare`     | a Type checked against a TypeScript type you [declare](/docs/declare) |
| `type.define`      | your definition, unchanged, type-checked as `type` would check it     |
| `type.raw`         | `type` without type-level parsing, for dynamic definitions            |
| `type.schema`      | a Type from an `@ark/schema` [schema](/docs/internals/schemas)        |
| `type.scope`       | a [scope](/docs/scopes), the same as `scope`                          |
| `type.module`      | a [module](/docs/scopes#modules), the scope's exported aliases        |
| `type.keywords`    | every [keyword](/docs/keywords), e.g. `type.keywords.string.email`    |
| `type.errors`      | the `ArkErrors` class, for `out instanceof type.errors`               |
| `type.hkt`         | the `Hkt` class for [higher-kinded generics](/docs/generics#hkt)      |
| `type.$`           | the scope `type` parses definitions in                                |
| `type.string`, ... | root keywords like `string`, `Date` and `Record` as Types or generics |

```ts
// Type<"foo">
const Foo = type.unit("foo")

// Type<"a" | 1 | null>
const Some = type.enumerated("a", 1, null)

// Type<string | number>
const StringOrNumber = type.or("string", "number")

// Type<{ a: 3; b: 2; c: 4 }>
const Merged = type.merge({ a: "1", b: "2" }, { a: "3", c: "4" })

// Type<Map<unknown, unknown>>
const AnyMap = type.instanceOf(Map)

// Type<any>, since the definition is only parsed at runtime
const Dynamic = type.raw("number")

// { name: "string" }, checked like a definition passed to type
const userDef = type.define({ name: "string" })
```

`type.valueOf` skips the reverse mappings TypeScript adds to a numeric `enum`:

```ts
enum Color {
	Red,
	Green = "green"
}

// Type<Color>, allowing 0 and "green" but not "Red"
const AnyColor = type.valueOf(Color)
```

---

### Ark Docs Package.Json (`ark/docs/package.json`)

{
	"name": "@ark/docs",
	"version": "0.0.1",
	"private": true,
	"type": "module",
	"scripts": {
		"build": "next build",
		"dev": "next dev",
		"buildAndStart": "pnpm build && pnpm start",
		"start": "pnpm serve out",
		"clean": "rm -rf .next out .cache",
		"upDeps": "pnpm up --latest",
		"checkLinks": "linkinator https://arktype.io -r"
	},
	"dependencies": {
		"@ark/aot": "workspace:*",
		"@ark/attest": "workspace:*",
		"@ark/fast-check": "workspace:*",
		"@ark/fs": "workspace:*",
		"@ark/json-schema": "workspace:*",
		"@ark/repo": "workspace:*",
		"@ark/schema": "workspace:*",
		"@ark/util": "workspace:*",
		"@icons-pack/react-simple-icons": "12.7.0",
		"@mdx-js/mdx": "3.1.1",
		"@monaco-editor/react": "4.7.0",
		"@shikijs/transformers": "4.5.0",
		"@shikijs/twoslash": "4.5.0",
		"arkdark": "workspace:*",
		"arkregex": "workspace:*",
		"arksets": "workspace:*",
		"arkthemes": "workspace:*",
		"arktype": "workspace:*",
		"class-variance-authority": "0.7.1",
		"github-slugger": "2.0.0",
		"hast-util-to-jsx-runtime": "2.3.6",
		"hast-util-to-string": "3.0.1",
		"linkinator": "6.1.2",
		"lucide-react": "0.503.0",
		"mdast-util-from-markdown": "2.1.0",
		"mdast-util-gfm": "3.1.0",
		"mdast-util-to-hast": "13.2.1",
		"mdast-util-to-markdown": "2.2.0",
		"mdast-util-to-string": "4.0.0",
		"micromark-extension-gfm": "3.0.0",
		"minisearch": "7.2.0",
		"monaco-editor": "0.52.2",
		"monaco-editor-textmate": "4.0.0",
		"monaco-textmate": "3.0.1",
		"next": "16.4.1",
		"onigasm": "2.2.5",
		"postcss": "8.5.3",
		"posthog-js": "1.237.0",
		"prettier": "3.5.3",
		"react": "19.2.9",
		"react-dom": "19.2.9",
		"remark-gfm": "4.0.1",
		"remark-mdx": "3.1.1",
		"remark-parse": "11.0.0",
		"serve": "14.2.4",
		"shiki": "4.5.0",
		"twoslash": "0.3.9",
		"unified": "11.0.5",
		"unist-util-visit": "5.1.0",
		"yaml": "2.9.1"
	},
	"devDependencies": {
		"@hono/standard-validator": "0.4.0",
		"@hookform/resolvers": "5.9.1",
		"@modelcontextprotocol/server": "2.3.1",
		"@orpc/arktype": "1.15.7",
		"@orpc/openapi": "1.15.7",
		"@orpc/server": "1.15.7",
		"@resvg/resvg-js": "2.6.2",
		"@standard-schema/spec": "1.0.0",
		"@tailwindcss/postcss": "4.1.4",
		"@trpc/server": "11.19.0",
		"@types/fontkit": "2.0.9",
		"@types/hast": "3.0.5",
		"@types/mdast": "4.0.4",
		"@types/mdx": "2.0.13",
		"@types/react": "19.2.18",
		"@types/react-dom": "19.2.7",
		"@types/wawoff2": "1.0.2",
		"ai": "7.0.140",
		"drizzle-arktype": "0.1.3",
		"drizzle-orm": "0.45.4",
		"esbuild": "0.25.10",
		"fast-check": "3.23.2",
		"fontkit": "2.0.4",
		"hono": "4.13.13",
		"mdast-util-mdx-jsx": "3.2.0",
		"react-hook-form": "7.90.0",
		"tailwindcss": "4.1.4",
		"terser": "5.51.2",
		"typescript": "catalog:ts6",
		"valibot": "1.1.0",
		"wawoff2": "2.0.1",
		"zod": "4.1.12"
	}
}

---

### Ark Docs Tsconfig.Json (`ark/docs/tsconfig.json`)

{
	"extends": "../../tsconfig.json",
	"compilerOptions": {
		// unfortunately, twoslash doesn't seem to respect customConditions,
		// so .d.ts will need to be rebuilt to see its static compilation updated
		"module": "ESNext",
		"moduleResolution": "bundler",
		"allowJs": true,
		"jsx": "preserve",
		// we don't need declarations for docs, and enabling it causes
		// pnpm resolution errors
		"declaration": false,
		"lib": ["ESNext", "DOM"],
		"plugins": [
			{
				"name": "next"
			}
		],
		"incremental": true
	},
	"mdx": {
		"checkMdx": true
	},
	"include": [
		"next.config.ts",
		"next-env.d.ts",
		"**/*.ts",
		"**/*.tsx",
		".next/types/**/*.ts"
	],
	"exclude": ["node_modules", "out"],
	"customConditions": ["ark-ts"]
}

---

### Ark Docs Public Llms Full (`ark/docs/public/llms-full.txt`)

# ArkType

> TypeScript's 1:1 validator

# Setup

> Install ArkType, define a Type and precompile it in your bundler.

## Install

```bash
npm install arktype
```

```bash
npm install -D @ark/aot
```

`arktype` is a dependency and `@ark/aot` a dev dependency. `arktype` defines and validates Types. [`@ark/aot`](https://arktype.io/docs/precompile) precompiles them when you build, so arktype's parser never ships and nothing compiles at runtime. Skip it for a script or REPL with no build step: every Type works without it.

## Define a Type

```ts
import { type } from "arktype"

export const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

const out = User({ name: "Alan", age: -1 })

if (out instanceof type.errors) console.error(out.summary)
```

## Add the plugin

**Vite**

```ts
import { precompile } from "@ark/aot/unplugin"
import { defineConfig } from "vite"

export default defineConfig({
	plugins: [precompile.vite()]
})
```

Vitest runs your tests through the same plugin.

**Next.js**

```js
import { withPrecompile } from "@ark/aot/turbopack"

export default withPrecompile({
	// for the pages router
	bundlePagesRouterDependencies: true,
	turbopack: {
		rules: {
			"*.ts": { loaders: ["@ark/aot/turbopack"] },
			"*.tsx": { loaders: ["@ark/aot/turbopack"] },
			"*.{js,mjs}": {
				condition: { content: /arktype/ },
				loaders: ["@ark/aot/turbopack"]
			}
		},
		resolveAlias: {
			arktype: "arktype/runtime",
			"arktype/codecs": "arktype/runtime",
			"arktype/config": "arktype/runtime",
			"arktype/errors": "arktype/runtime",
			"arktype/mutatesInput": "arktype/runtime",
			"@ark/schema/runtime": "@ark/aot/turbopack/runtime"
		}
	}
})
```

For `next build --webpack`, see [Next.js](https://arktype.io/docs/precompile/setup#next).

**esbuild**

```ts
import { precompile } from "@ark/aot/unplugin"
import { build } from "esbuild"

await build({
	entryPoints: ["src/main.ts"],
	bundle: true,
	outfile: "dist/main.js",
	plugins: [precompile.esbuild()]
})
```

**Rolldown**

```ts
import { precompile } from "@ark/aot/unplugin"
import { defineConfig } from "rolldown"

export default defineConfig({
	input: "src/main.ts",
	output: { file: "dist/main.js" },
	plugins: [precompile.rolldown()]
})
```

**Rollup**

```js
import { precompile } from "@ark/aot/unplugin"
import { nodeResolve } from "@rollup/plugin-node-resolve"
import typescript from "@rollup/plugin-typescript"

export default {
	input: "src/main.ts",
	output: { file: "dist/main.js", format: "es" },
	plugins: [
		precompile.rollup(),
		nodeResolve({ extensions: [".ts", ".js"] }),
		typescript()
	]
}
```

**webpack**

```js
import { precompile } from "@ark/aot/unplugin"

export default {
	entry: "./src/main.ts",
	resolve: { extensions: [".ts", ".js"] },
	module: {
		rules: [
			{ test: /\.ts$/, loader: "ts-loader", options: { transpileOnly: true } }
		]
	},
	plugins: [precompile.webpack()]
}
```

**Bun**

```ts
import { precompile } from "@ark/aot/unplugin"

await Bun.build({
	entrypoints: ["src/main.ts"],
	outdir: "dist",
	target: "bun",
	plugins: [precompile.bun()]
})
```

Bun's bundler needs Bun 1.2.22 or later. To precompile as `bun test` or `bun run` loads your code, see [Bun](https://arktype.io/docs/precompile/setup#bun).

**Node**

```ts
import { register } from "@ark/aot/node"

register()
```

```sh
node --import ./register.ts src/main.ts
```

Node 22.15 or later. A program `tsc` compiles for production precompiles with [`arktype-precompile --emit`](https://arktype.io/docs/precompile/setup#tsc).

Rspack, Rsbuild, Farm and the rest are in [Setup](https://arktype.io/docs/precompile/setup).

## Run it

Build or start your dev server as you already do. `User` is now a standalone validator, and the program prints:

```
age must be non-negative
```

A precompiled error reads as arktype's does at runtime: what failed, without printing the value.

To see what the build makes of each definition without bundling, run:

```sh
npx arktype-precompile --check
```

```
src/user.ts:3:21  accepted
1 site in 2 files: 1 accepted (100.0%)
```

A definition the build can't precompile fails it, naming the file, the line and the fix. See [Troubleshooting](https://arktype.io/docs/precompile/troubleshooting).

## Configure TypeScript

TypeScript `>=5.1`, including TypeScript 7, with:

```json
{
	"compilerOptions": {
		"strict": true,
		"skipLibCheck": true,
		"exactOptionalPropertyTypes": true
	}
}
```

- [`strict`](https://www.typescriptlang.org/tsconfig#strict), or at least [`strictNullChecks`](https://www.typescriptlang.org/tsconfig#strictNullChecks), is required for inference to work.
- [`skipLibCheck`](https://www.typescriptlang.org/tsconfig#skipLibCheck) is recommended. It avoids harmless errors from differences between your config and ours (see [FAQ](https://arktype.io/docs/faq#why-do-i-see-type-errors-in-an-arktype-package-in-node_modules)) and speeds up your editor.
- [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes) is recommended. It makes your inferred types match runtime behavior. ArkType rejects `undefined` for an optional key unless its value allows it, so without this flag, `typeof User.infer` accepts `{ age: undefined }` while `User` rejects it.

ArkType is ESM-only, but a CommonJS project can `require` it on runtimes that support `require(esm)`, like Node `>=20.19` or `>=22.12`. TypeScript allows that `require` under `"module": "nodenext"` from 5.8, where `node16` reports TS1479. `@ark/aot` runs on Node 22.12 or later.

## Runtimes

ArkType runs in Node, Deno, Bun, browsers and edge runtimes like Cloudflare Workers. A precompiled validator never generates code, so it runs under a Content-Security-Policy that blocks `eval`. Without precompiling, ArkType validates without compiling where `new Function` is blocked, including within a Cloudflare Workers request, which is [up to about 30x slower](https://arktype.io/docs/configuration#jitless) per call on a plain object; under a strict policy, enable [`jitless`](https://arktype.io/docs/configuration#jitless) so it never tries `new Function`, which the policy would report.

## Next

- Set up [your editor](https://arktype.io/docs/editor), and give your agent the [ArkType skill](https://arktype.io/docs/agents).
- Learn the syntax, starting with [your first type](https://arktype.io/docs/intro/your-first-type).
- Configure ArkType globally in a module that loads before anything creates a Type. See [Configuration](https://arktype.io/docs/configuration).
- Coming from Zod or another validator? See [Migrating](https://arktype.io/docs/migrating). From an earlier ArkType? See [Upgrading](https://arktype.io/docs/upgrading).

# Your first type

> Define a type with TypeScript syntax, compose it, and validate data with it.

If you already know TypeScript, you already know most of ArkType's syntax.

## Define

```ts
import { type } from "arktype"

const User = type({
	name: "string",
	platform: "'android' | 'ios'",
	"versions?": "(number | string)[]"
})

// { name: string; platform: "android" | "ios"; versions?: (number | string)[] }
type User = typeof User.infer
```

A key ending in `?` is optional, as in TypeScript. String literals like `'android'` need their own quotes inside the definition.

Definitions are checked by TypeScript, so a mistake is an error in your editor, with autocomplete to help fix it:

```ts
const User = type({
	name: "strng"
	// TypeScript: 'strng' is unresolvable
})
```

## Compose

Suppose we want to move `platform` and `versions` from our original type to a new `device` property.

```ts
const User = type({
	name: "string",
	// nested definitions don't need to be wrapped
	device: {
		platform: "'android' | 'ios'",
		"versions?": "(number | string)[]"
	}
})
```

To decouple `device` from `User`, move it to its own type and reference it.

```ts
const Device = type({
	platform: "'android' | 'ios'",
	"versions?": "(number | string)[]"
})

const User = type({
	name: "string",
	device: Device
})
```

## Validate

Call a type with `unknown` data to get back either the validated data or an `ArkErrors` object describing every problem.

```ts
const out = User({
	name: "Alan Turing",
	device: {
		platform: "enigma",
		versions: [0, "1", 0n]
	}
})

if (out instanceof type.errors) {
	// ArkErrors: device.platform must be "android" or "ios"
	//            device.versions[2] must be a number or a string
	console.error(out.summary)
} else {
	// out is narrowed to the validated User
	console.log(`Hello, ${out.name}`)
}
```

Calling a type never throws for invalid data. Each problem is in `out.issues`, with its `path`, `code` and `message`; see [Errors](https://arktype.io/docs/errors).

Where invalid data is a bug rather than something to handle, use `.assert`. It returns the validated data or throws a `TraversalError` describing the same problems.

```ts
// TraversalError: name must be a string (was missing)
const user = User.assert({})
```

You now know how to define a `Type` and use it to check your data at runtime.

Next, we'll look at how ArkType extends TypeScript's type system with runtime constraints like `string.email` or `number.integer < 100`.

# Adding constraints

> Narrow types beyond what TypeScript can express, with keywords, ranges, divisors and custom predicates.

TypeScript can represent types like `string` or `number`, but what about `email` or `integer less than 100`?

In ArkType, conditions that narrow a type beyond its **basis** are called **constraints**. They compose with TypeScript's operators like any other part of a definition.

## Define

Let's create a new `Contact` Type that enforces our example constraints.

```ts
const Contact = type({
	// many common constraints are available as built-in keywords
	email: "string.email",
	// others can be written as type-safe expressions
	score: "number.integer < 100"
})

// infer the TypeScript type as usual
type Contact = typeof Contact.infer
```

> **number excludes NaN and Infinity**
>
> `number` rejects `NaN`, `Infinity` and `-Infinity` by default. To allow them, see `number.NaN`, `number.Infinity` and `number.NegativeInfinity` in [Keywords](https://arktype.io/docs/keywords), or the `numberAllowsNaN` and `numberAllowsInfinity` options in [Configuration](https://arktype.io/docs/configuration).

## Compose

Imagine we want to define a new Type representing a non-empty list of `Contact`.

Definitions create new types. Chained methods refine or transform types you already have.

```ts
// a non-empty list of Contact
const Contacts = Contact.array().atLeastLength(1)

// ArkErrors: must be non-empty
const out = Contacts([])
```

## Narrow

Structured constraints like divisors and ranges will only take us so far. For anything else, add your own logic with `.narrow`.

```ts
// there's no "not divisible" expression - need to narrow
const Odd = type("number").narrow((n, ctx) =>
	// if even, add a customizable error and return false
	n % 2 === 0 ? ctx.mustBe("odd") : true
)

const FavoriteNumbers = type({
	even: "number % 2",
	odd: Odd
})

const out = FavoriteNumbers({
	even: 7,
	odd: 8
})

if (out instanceof type.errors) {
	// ArkErrors: even must be even
	//            odd must be odd
	console.error(out.summary)
} else {
	console.log(out.odd)
}
```

You now know how to refine your types to enforce additional constraints at runtime.

But what if once your input is fully validated, you still need to make some adjustments before it's ready to use?

The final section of the intro covers **morphs**, which transform data as part of a Type.

# Morphs

> Transform data as part of validation by piping it through functions and other Types.

Sometimes, data at the boundaries of your code needs more than validation before it's ready to use.

**Morphs** transform your data. You can **pipe** them before, after or between validators, and chain them to other morphs.

```ts
// Type<(In: string) => Out<object>>
const parseJson = type("string").pipe((s): object => JSON.parse(s))

// { ark: "type" }
const out = parseJson('{ "ark": "type" }')

// ArkErrors: must be a string
const badOut = parseJson(out)
```

This is a good start, but what happens if we pass a string that isn't valid JSON?

```ts
// Uncaught SyntaxError: Expected property name ☠️
const badOut = parseJson('{ unquoted: "keys" }')
```

By default, ArkType assumes that if one of your morphs or narrows throws, you intend to crash. For a function you don't trust, use `pipe.try`, which turns what it throws into an error:

```ts
const parseJson = type("string").pipe.try((s): object => JSON.parse(s))

const out = parseJson('{ unquoted: "keys" }')

if (out instanceof type.errors) {
	// ArkErrors: must be valid according to an anonymous predicate (SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3))
	console.error(out.summary)
}
```

A validated `object` still isn't very useful, though. Since a Type can be called like a function, it can be a step in a pipe too. For JSON, the built-in `string.json.parse` keyword does the parsing, and `.to` validates its output:

```ts
// .to is a sugared .pipe for a single parsed output validator
const parseJson = type("string.json.parse").to({
	name: "string",
	version: "string.semver"
})

const out = parseJson('{ "name": true, "version": "v2.0.0" }')

if (out instanceof type.errors) {
	// ArkErrors: name must be a string
	//            version must be a semantic version (see https://semver.org/)
	console.error(out.summary)
} else {
	// { name: string; version: string }
	console.log(`${out.name}:${out.version}`)
}
```

> **Morphs receive your data, not a copy**
>
> A morph is passed the validated value itself. If it mutates its argument, it mutates the caller's data, so return a new value instead.

```ts
const addTag = type({ tags: "string[]" }).pipe(o => ({
	...o,
	tags: [...o.tags, "new"]
}))
```

When you're ready to ship, [precompile](https://arktype.io/docs/precompile) your Types: the same definitions, compiled when you build into standalone validators that carry only the checks they need.

You now have the fundamentals you need to bring your types to runtime. The rest of the docs cover each part of the API in depth, starting with [primitives](https://arktype.io/docs/primitives).

# Cheat sheet

> ArkType's most common syntax, patterns and gotchas on one page.

A quick reference for ArkType's most common patterns. The [skill for agents](https://arktype.io/docs/agents) covers the same ground.

## Syntax kinds

ArkType offers several ways to define the same type. Use whichever fits your context.

```ts
import { type } from "arktype"

// string expression, the most concise
const StringSyntax = type("string | number")

// tuple expression, for operands that aren't strings
const TupleSyntax = type(["string", "|", "number"])

// chained, to compose existing types
const Chained = type("string").or("number")
```

## Keywords

Keywords follow a `typescriptType.constraint.subconstraint` pattern. See [Keywords](https://arktype.io/docs/keywords) for the full list.

```ts
// string keywords
type("string.email") // email address
type("string.uuid") // UUID
type("string.url") // parsable URL
type("string.trim") // morph: trims whitespace
type("string.json.parse") // morph: string → parsed JSON
type("string.date.parse") // morph: string → Date

// number keywords
type("number.integer") // whole numbers
type("number.safe") // between MIN_SAFE_INTEGER and MAX_SAFE_INTEGER, not necessarily an integer
type("number.epoch") // integer ms timestamp a Date can hold
```

`number` rejects `NaN`, `Infinity` and `-Infinity`. Add `number.NaN`, `number.Infinity` or `number.NegativeInfinity` to allow them.

## Operators

```ts
type("string | number") // union
type("string.email & /@arktype\\.io$/") // intersection
type("number > 0") // exclusive min
type("number >= 0") // inclusive min
type("string <= 255") // max length
type("number != 0") // excludes 0
type("number % 2") // divisible by 2
```

## Objects

```ts
const User = type({
	name: "string",
	"email?": "string.email", // optional: '?' goes on the key
	age: "number >= 0 = 0" // defaultable, so optional in the input
})

// index signatures (Record types)
const Env = type({
	"[string]": "string" // Record<string, string>
})

// undeclared keys are allowed by default; reject or remove them
const Strict = type({ "+": "reject", name: "string" })
const Stripped = type({ "+": "delete", name: "string" })
```

## Arrays and tuples

```ts
const Strings = type("string[]") // string expression
const Numbers = type.number.array() // chained

// tuples: fixed length, a type per position
const Pair = type(["string", "number"])

// type([X]) is a 1-element tuple, not an array
const Item = type({ id: "string" })
const Wrong = type([Item]) // tuple of exactly [Item]
const Right = Item.array() // Item[]

// readonly
const Ids = type("string[]").readonly() // readonly string[]
```

## Enumerations

```ts
const Role = type("'admin' | 'member'") // literals need their own quotes
const Size = type.enumerated(1, 2, 3)

enum Color {
	Red = "red",
	Blue = "blue"
}
const ColorValue = type.valueOf(Color)
```

## Composition

```ts
const Device = type({
	platform: "'android' | 'ios'",
	"version?": "string"
})

// reference in another type by passing it directly
const User = type({
	name: "string",
	device: Device
})

// fluent composition
const Admin = User.and({ role: "'admin'" })
const Guest = type({ name: "string" }).or({ token: "string" })
const Draft = User.partial()
const Name = User.pick("name")
```

## Recursive types

```ts
import { scope } from "arktype"

const types = scope({
	TreeNode: {
		value: "number",
		children: "TreeNode[]"
	}
}).export()

const tree = types.TreeNode({ value: 1, children: [] })
```

## Morphs and pipes

```ts
// .to(): parse, then validate the output
const parsePort = type("string.integer.parse").to("0 < number <= 65535")

// .pipe(): validate, then transform
const toUpper = type("string").pipe(s => s.toUpperCase())

// built-in parse morphs
const parseDate = type("string.date.parse") // string → Date
const parseJson = type("string.json.parse") // string → parsed JSON
const trim = type("string.trim") // string → trimmed string
```

## Custom rules

```ts
const Signup = type({
	password: "string >= 8",
	confirmPassword: "string"
}).narrow(
	(data, ctx) =>
		data.password === data.confirmPassword ||
		ctx.reject({
			expected: "identical to password",
			actual: "",
			path: ["confirmPassword"]
		})
)
```

## Matching

```ts
import { match } from "arktype"

const sizeOf = match({
	string: s => s.length,
	number: n => n,
	default: "assert"
})

sizeOf("abc") // 3
```

## Type inference

```ts
const User = type({
	name: "string",
	"age?": "number"
})

// extract the TypeScript type
type User = typeof User.infer
// { name: string; age?: number }
```

## Error handling

```ts
const User = type({
	name: "string",
	"age?": "number"
})

const out = User({ name: "Alan", age: "not a number" })

if (out instanceof type.errors) {
	// ArkErrors: age must be a number
	console.error(out.summary)
	// plain objects, each with its path, code and message
	out.issues[0].path
} else {
	// out is typed as { name: string; age?: number }
	console.log(out.name)
}

// returns the validated data or throws
const user = User.assert({ name: "Alan" })
```

## Interop

```ts
// a Standard Schema, accepted by tRPC, Hono, oRPC, the MCP SDK and others
User["~standard"]

// { $schema: "...", type: "object", properties: { ... }, required: ["name"] }
User.toJsonSchema()
```

Global configuration goes through `configure` from `arktype/config`, in a file imported before anything creates a Type. See [Configuration](https://arktype.io/docs/configuration).

## Precompile

```ts
// vite.config.ts: every Type becomes a standalone validator at build time
export default {
	plugins: [precompile.vite()]
}
```

## Common gotchas

| Mistake | Fix |
| - | - |
| `name: "string \| undefined"` for optional | Use `"name?": "string"`: `?` goes on the **key** |
| `type([Schema])` for arrays | Use `Schema.array()`: brackets create tuples |
| ``type(`${Schema}[]`)`` | Use `Schema.array()` or `[Schema, "[]"]`, never interpolate a Type |
| `"Record<string, T>"` with `T` a variable | Use `type.Record("string", T)` or `{ "[string]": T }` |
| `type("number = 0")` | Defaults only work as object values or tuple elements |
| `out[0]` or `out.map(...)` on errors | Use `out.issues[0]` or `out.issues.map(...)` |
| Mutating the argument in `.pipe` | Return a new value; a morph receives the caller's data, not a copy |
| `type User = typeof Schema.t` | Use `typeof Schema.infer` for the output type |
| Precompiled: `User.pick(...keys)` with `keys` known only at runtime | A Type per case, composed from static values: `const Admin = User.and({ role: "'admin'" })` |
| Precompiled: `type()` from a runtime value | Make it static, mark it `// @ark-runtime`, or build with `runtime: "arktype"` |

# Agents

> Help Claude Code, Codex, Cursor and other coding agents write ArkType.

Every error ArkType reports names its fix: `tsc`'s as a definition is written, a [precompiled](https://arktype.io/docs/precompile) build's and validation's. An agent can close each loop on its own, which is also why precompiling costs little with one: the build step is one more loop it already runs.

## Skill

The ArkType [skill](https://github.com/arktypeio/arktype/blob/main/ark/type/skills/arktype/SKILL.md) tells agents when to reach for ArkType, how its syntax maps to TypeScript, and which mistakes to avoid. Add it to your project with:

```bash
npx skills add arktypeio/arktype
```

This installs the skill from the repository's default branch, which tracks the latest release. The `arktype` package also includes the skill at `skills/arktype/SKILL.md`, so tools like [skills-npm](https://github.com/antfu/skills-npm) can link the copy that matches your installed version.

Agents read two references the skill links when a task needs them: the [migration guide](https://arktype.io/docs/migrating), when they convert schemas from Zod, Valibot, TypeBox, Yup, Joi, Effect Schema or JSON Schema, and a precompile guide with the setup for each bundler, Next.js and test runner and the fix for each build error.

## Migrate from Zod

With the skill installed, migrate in one prompt:

```
Migrate this project from Zod to ArkType.
```

The agent follows [Migrating a project](https://arktype.io/docs/migrating#migrating-a-project): it rewrites each schema where it is, keeping what it accepts, rejects and returns, swaps integrations like `zodResolver` for their Standard Schema versions, and keeps Zod where a dependency accepts only it, like the MCP SDK before v2. Review its summary, which lists what still behaves differently and any test it updated, like a JSON Schema snapshot whose keys are now in canonical order.

To precompile in the same pass, ask for both:

```
Migrate this project from Zod to ArkType and precompile it.
```

## Docs as Markdown

Every page of these docs is available as Markdown by adding `.md` to its URL, e.g. [/docs/intro/setup.md](https://arktype.io/docs/intro/setup.md). The Copy page button beside each page's title copies it, and its menu opens it in Claude, ChatGPT or Cursor.

[/llms.txt](https://arktype.io/llms.txt) is an index of every page, with a link to its Markdown and a one-line description, following the [llms.txt](https://llmstxt.org) convention. [/llms-full.txt](https://arktype.io/llms-full.txt) has the full text of every ArkType page in one file. Precompile, ArkRegex, Attest, JSON Schema, ArkSets and Internals each have a file like it at their section's URL plus `/llms.txt`, like [/docs/precompile/llms.txt](https://arktype.io/docs/precompile/llms.txt).

## Precompile

A [precompiled](https://arktype.io/docs/precompile) build reports each definition it can't precompile with its file, line and column, the reason and the fix. [With agents](https://arktype.io/docs/precompile#with-agents) shows one and the tools that shorten the loop: `arktype-precompile --check`, the ESLint rule and shadow mode. [Troubleshooting](https://arktype.io/docs/precompile/troubleshooting) lists the fix for each report.

## AGENTS.md

Agents that don't load skills still read your `AGENTS.md` or `CLAUDE.md`. Paste this in to keep them on ArkType when they add validation:

```md
## Validation

- Validate untrusted input, like request bodies, form data, env vars and JSON, with ArkType. Docs: https://arktype.io/llms.txt
- Derive each TypeScript type from its validator with `typeof T.infer` rather than writing it by hand.
```

If you precompile, add:

```md
- ArkType definitions are precompiled by @ark/aot when the app builds. Fix each precompile error as its last line says, and don't set allowUnsafe or runtime: "arktype" to get past one. `npx arktype-precompile --check src` lists them without building. Setup and fixes: https://arktype.io/docs/precompile/llms.txt
```

## Building agents

ArkType types are [Standard Schemas](https://arktype.io/docs/standard-schema) that can also produce JSON Schema, so libraries that need both accept them directly. For example, the [MCP TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/advanced/schema-libraries) (`@modelcontextprotocol/server`) takes an ArkType type as a tool's `inputSchema` as-is. It derives the JSON Schema the model sees from it, and validates the model's arguments before your handler runs:

```ts
// server is an McpServer from @modelcontextprotocol/server
server.registerTool(
	"greet",
	{
		description: "Greet someone by name",
		inputSchema: type({ name: "string", "times?": "1 <= number.integer <= 5" })
	},
	async ({ name, times }) => ({
		content: [{ type: "text", text: `Hello, ${name}! `.repeat(times ?? 1) }]
	})
)
```

Calling `greet` with `times: 99` returns an error result to the model with ArkType's message, `times must be at most 5`, so it knows what to fix.

A [precompiled](https://arktype.io/docs/precompile) validator ships `~standard.jsonSchema`, which the SDK reads to describe the tool, as the build sees the SDK read it.

# Editor setup

> Highlighting, inline errors and autocomplete for ArkType definitions in VS Code, JetBrains IDEs and other editors.

ArkType works in any editor with TypeScript support. These extensions make definitions read like the rest of your code.

## VS Code

Install [ArkType](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkdark) (`arktypeio.arkdark`). It's also on [Open VSX](https://open-vsx.org/extension/arktypeio/arkdark) for Cursor, VSCodium and Windsurf. It adds:

- syntax highlighting for strings in ArkType definitions, in `.ts`, `.tsx`, `.js`, `.jsx`, `.mdx`, `.svelte`, `.vue`, `.astro` and Markdown files
- one-line summaries of ArkType's type errors at the end of the line, through [ErrorLens](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens), which it installs as a dependency
- the setting `"editor.quickSuggestions": { "strings": "on" }`, so you get completions while typing an expression like `"string | num"`

It also sets ErrorLens to show the message of the problem closest to your cursor, with no delay and without the hover buttons, and to show only the part of an ArkType error that names the fix, like `"number | string"` for `"number | strin"`. Each is an ordinary default, so a value in your own settings for `errorLens.followCursor`, `errorLens.delay`, `errorLens.editorHoverPartsEnabled` or `errorLens.replace` overrides it.

To have auto-import pick ArkType's `type` instead of the `type` function from Node's `os` module, add this to `.vscode/settings.json`:

```json
{
	"typescript.preferences.autoImportSpecifierExcludeRegexes": ["^(node:)?os$"]
}
```

### Themes

[ArkThemes](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkthemes) (`arktypeio.arkthemes`, also on [Open VSX](https://open-vsx.org/extension/arktypeio/arkthemes)) is a separate extension with **ArkDark**, which these docs use for code, and **ArkLight**, each with an italic variant. They highlight TypeScript generics distinctly. You don't need them for the ArkType extension to work.

## JetBrains IDEs

The [ArkType plugin](https://plugins.jetbrains.com/plugin/27099-arktype), maintained by Jan-Niklas Wortmann, adds syntax highlighting for ArkType definitions to WebStorm, IntelliJ IDEA and other JetBrains IDEs.

## Other editors

There's no official extension for other editors yet. For Neovim, a community [tree-sitter grammar](https://github.com/jeffrom/tree-sitter-arktype) covers the most common syntax. If you'd like to help add support for another editor, see [this issue](https://github.com/arktypeio/arktype/issues/989).

Completions and type errors come from TypeScript, so they work in every editor without an extension.

# Migrating

> Migrate a project from Zod with one prompt, or convert schemas from Zod, Valibot, TypeBox, Yup, Joi, Effect Schema and JSON Schema to ArkType by hand, and the defaults that differ between them.

Add the [ArkType skill](https://arktype.io/docs/agents#skill) to your project:

```bash
npx skills add arktypeio/arktype
```

Then ask your agent:

```
Migrate this project from Zod to ArkType.
```

The skill includes this page, and your agent works through [Migrating a project](https://arktype.io/docs/migrating#migrating-a-project): it converts each schema where it is, keeping what it accepts, rejects and returns, updates the code that calls it and swaps integrations like `zodResolver`. Before removing `zod`, it compares each schema your tests don't cover with its Zod original on the same inputs, then runs your typecheck and tests. Where a dependency accepts only Zod, like the MCP SDK before v2, it keeps Zod for that call. Its summary lists anything that still behaves differently, like error message text.

To [precompile](https://arktype.io/docs/precompile) in the same pass, ask for both:

```
Migrate this project from Zod to ArkType and precompile it.
```

To convert by hand, start with the example below, then the [Zod table](https://arktype.io/docs/migrating#zod) and [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ).

## Zod side by side

A Zod schema and its ArkType equivalent:

```ts
import { z } from "zod"

const User = z.object({
	name: z.string().min(1),
	email: z.email(),
	age: z.number().int().nonnegative().optional(),
	role: z.enum(["admin", "member"]).default("member")
})

type User = z.infer<typeof User>

const result = User.safeParse(data)

if (!result.success) console.error(result.error.issues)
```

```ts
import { type } from "arktype"

const User = type({
	// z.object() removes undeclared keys
	"+": "delete",
	name: "string >= 1",
	email: "string.email",
	// .optional() accepts undefined too
	"age?": "number.integer >= 0 | undefined",
	role: "'admin' | 'member' = 'member'"
})

type User = typeof User.infer

const out = User(data)

if (out instanceof type.errors) console.error(out.issues)
```

`.parse(data)` is `User.assert(data)`. The [Zod table](https://arktype.io/docs/migrating#zod) maps the rest of the API, and [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ) lists what to write where the two libraries' defaults disagree, like `"+": "delete"` above. One the example leaves as is: Zod also applies `role`'s default when the key is present as `undefined`, which ArkType rejects.

## Zod

Zod Mini spells most methods as functions, so `z.optional(z.string())` maps like `z.string().optional()`, and `z.string().check(z.minLength(1))` like `z.string().min(1)`.

| Zod | ArkType |
| - | - |
| `z.string()`, `z.number()`, `z.boolean()`, `z.null()` | `"string"`, `"number"`, `"boolean"`, `"null"` |
| `z.bigint()`, `z.symbol()`, `z.undefined()`, `z.void()` | `"bigint"`, `"symbol"`, `"undefined"`, `"undefined"` |
| `z.unknown()`, `z.any()`, `z.never()` | `"unknown"`, `"unknown.any"`, `"never"` |
| `z.literal("a")`, `z.literal(0.5)` | `"'a'"`, `"0.5"` |
| `z.enum(["a", "b"])` | `"'a' \| 'b'"` or `type.enumerated("a", "b")` |
| `z.nativeEnum(E)`, `z.enum(E)` | `type.valueOf(E)` |
| `z.object({ ... })` | `type({ ... })`, nested objects as plain objects |
| `.optional()` on a property | `"key?": "T \| undefined"` |
| `.optional()` anywhere else | `"T \| undefined"` or `T.or("undefined")` |
| `.nullable()`, `.nullish()` | `"T \| null"`, `"key?": "T \| null \| undefined"` |
| `.default(x)` on a property | `key: "number = 0"` or `key: T.default(x)` |
| `.catch(x)` | a `.pipe()` that returns `x` for invalid input, see [Fallbacks](https://arktype.io/docs/migrating#semantics-to-check) |
| `z.array(T)`, `.min(1)`, `.nonempty()` | `"T[]"` or `T.array()`, `"string[] >= 1"` |
| `z.array(T).min(1)`, `T` a Type in a variable | `T.array().atLeastLength(1)` |
| `z.tuple([A, B])`, `.rest(C)` | `[A, B]`, `[A, B, "...", "C[]"]` |
| `z.union([A, B])`, `A.or(B)`, `z.discriminatedUnion` | `A.or(B)`, `"A \| B"` |
| `z.intersection(A, B)`, `A.and(B)` | `A.and(B)` |
| `z.record(z.string(), T)` | `"Record<string, T>"` or `{ "[string]": T }` |
| `z.record(z.enum(["a", "b"]), T)`, `z.partialRecord` | `{ a: T, b: T }`, `{ "a?": T, "b?": T }` |
| `z.set(T)`, `z.map(K, V)` | `"Set"`, `"Map"`, with a `.narrow()` that checks the entries |
| `.extend({ ... })`, `.merge(B)` | `.merge({ ... })` |
| `.pick`, `.omit`, `.partial`, `.required`, `.keyof` | same names |
| `.array()`, `.readonly()` | same names |
| `.strict()`, `z.strictObject` | `"+": "reject"` |
| `.passthrough()`, `z.looseObject` | the default |
| `.strip()`, the default `z.object` | `"+": "delete"` |
| `.catchall(T)` | `"[/^(?!a$\|b$)/]": T`, `a` and `b` the declared keys |
| `z.lazy(() => T)` | a scope or `this` |
| `.min(n)` / `.max(n)` / `.length(n)` on strings | `"string >= n"`, `"string <= n"`, `"string == n"` |
| `.nonempty()` on strings | `"string > 0"` |
| `.startsWith("a")`, `.endsWith("a")`, `.includes("a")` | `/^a/`, `/a$/`, `/a/`, escaping regex characters |
| `.int()` | `"number.integer & number.safe"`, or `"number.integer"` in Zod 3 |
| `.positive()`, `.nonnegative()`, `.gt(n)` | `"number > 0"`, `"number >= 0"`, `"number > n"` |
| `.min(n)` / `.max(n)` / `.lt(n)` on numbers | `"number >= n"`, `"number <= n"`, `"number < n"` |
| `.multipleOf(n)` | `"number % n"` |
| `.email()`, `.url()`, `.uuid()`, `.regex(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
| `.ip()` (Zod 3), `z.ipv4()`, `z.ipv6()` | `"string.ip"`, `"string.ip.v4"`, `"string.ip.v6"` |
| `.datetime()`, `z.iso.datetime()` | `"string.date.iso"` |
| `.trim()`, `.toLowerCase()`, `.toUpperCase()` | `"string.trim"`, `"string.lower"`, `"string.upper"` |
| `z.date()`, `z.instanceof(C)` | `"Date"`, `type.instanceOf(C)` |
| `.refine(fn, msg)`, `.superRefine(fn)` | `.narrow((v, ctx) => fn(v) \|\| ctx.reject({ message: msg }))` |
| `.transform(fn)`, `.pipe(T)` | `.pipe(fn)`, `.to(T)` |
| `z.preprocess(fn, T)` | `type("unknown").pipe(fn).to(T)` |
| `z.coerce.number()`, `z.coerce.date()` | `type("unknown").pipe(Number).to("number")`, see [Coercion](https://arktype.io/docs/migrating#semantics-to-check) |
| `z.coerce.string()`, `z.coerce.boolean()` | `type("unknown").pipe(String)`, `type("unknown").pipe(Boolean)` |
| `z.custom<T>(fn)` | `type("unknown").narrow((v): v is T => fn(v))` |
| `.brand<"Id">()` | `.brand("Id")` or `"string#Id"` |
| `.describe(text)`, `.meta({ title })` | a comment or `.configure({ title: text })` |
| `{ message }`, `{ error }`, `required_error` | `.configure({ message })`, or `.describe(...)` for "must be ..." |
| `z.infer`, `z.output`, `z.input` | `typeof T.infer`, `typeof T.inferIn` |
| `const T: z.ZodType<X> = ...` | no annotation: delete `X` and use `typeof T.infer` |
| `.parse(x)`, `.safeParse(x)` | `T.assert(x)`, `T(x)` then `instanceof type.errors` |
| `.parseAsync(x)`, `.safeParseAsync(x)` | the same, since ArkType is synchronous |
| `ZodError`, `error.issues` | `type.errors`, `out.issues` |
| `z.prettifyError(error)` | `out.summary` |
| `error.flatten()`, `z.flattenError(error)` | `out.issues` grouped by key, see [Update call sites](https://arktype.io/docs/migrating#migrating-a-project) |
| `z.ZodTypeAny` in a helper's signature | `type.Any` |

## Defaults that differ

| Behavior | ArkType | Zod | Valibot | TypeBox `Value.Check` | Yup | Joi | Effect Schema |
| - | - | - | - | - | - | - | - |
| Undeclared object keys | kept | removed | removed | allowed | kept | rejected | removed |
| Optional key present with the value undefined | rejected | accepted | accepted | accepted | accepted | accepted | accepted |
| Default applied when the value is undefined | no, only if absent | yes | yes | only `Value.Default` | yes | yes | yes |
| Converts input types, e.g. `"12"` to `12` | only when parsing | only in `z.coerce` | no | only `Value.Convert` | yes, unless strict | yes, unless convert false | no |
| `number` accepts `Infinity` | no | v4: no, v3: yes | yes | no | yes | no | yes |
| `number` accepts `NaN` | no | no | no | no | no | no | yes |
| An array where an object is expected | accepted | rejected | accepted | rejected | rejected | rejected | rejected |
| Empty string for a plain string | accepted | accepted | accepted | accepted | rejected if required | rejected | accepted |

What to write when the old behavior matters:

```ts
// remove undeclared keys like Zod, Valibot and Effect, for this object only
const Stripped = type({ "+": "delete", name: "string" })

// reject them like Joi or Zod's .strict()
const Strict = type({ "+": "reject", name: "string" })

// accept an explicit undefined as well as a missing key
const Patch = type({ "nickname?": "string | undefined" })

// apply a default when the key is missing or undefined
const Settings = type({
	theme: type("'light' | 'dark' | undefined")
		.pipe(v => v ?? "light")
		.default(undefined)
})

// allow non-finite numbers
const Measurement = type(
	"number | number.Infinity | number.NegativeInfinity | number.NaN"
)

// reject an array, which matches an object whose keys are all optional
const Filters = type({ "limit?": "number", "cursor?": "string" }).narrow(
	(o, ctx) => !Array.isArray(o) || ctx.reject("an object")
)

// count a string's length in code points, like Zod 4.5's .min(1).max(32)
const Title = type("string").narrow((s, ctx) => {
	const length = [...s].length
	return (length >= 1 && length <= 32) || ctx.reject("1 to 32 characters")
})
```

`"+"` applies to its own object, not to nested ones, and `.merge()` takes it from the object merged in, so repeat it there. To remove undeclared keys everywhere, as Zod does, set `onUndeclaredKey: "delete"` with `configure` from `arktype/config`, in a file imported before anything imports `arktype`.

Either way, an object that deletes keys transforms its input, so a union of such objects needs a key that tells them apart, like a literal `type`. Without one, data with both objects' keys could come out as either, so the union throws a `ParseError`. Where the old schema has no such key, delete outside the union. The result keeps every key either object declares, where Zod keeps only those of the first object that matches:

```ts
// z.union([z.object({ uri, text }), z.object({ uri, blob })])
const Contents = type({ "+": "ignore", uri: "string", text: "string" })
	.or({ "+": "ignore", uri: "string", blob: "string" })
	.to({ "+": "delete", uri: "string", "text?": "string", "blob?": "string" })
```

With `"delete"` or `"reject"`, from `"+"` or `configure`, an object's undeclared keys are `never`, so `.and()` with an object that has other keys throws. Add keys with `.merge()`.

## Semantics to check

**Transforms run in order.** `.pipe(fn)` transforms after validation, `.to(definition)` validates the result, and a `.narrow()` after a `.pipe()` sees the transformed value, like Zod's `.transform().refine()`. A narrow on an object whose properties transform sees the transformed properties.

```ts
// Zod: z.string().transform(s => s.length).refine(n => n > 2)
const Length = type("string")
	.pipe(s => s.length)
	.narrow(n => n > 2)

// Zod: z.preprocess(v => (typeof v === "string" ? v.split(",") : v), z.array(z.string()))
const Tags = type("string | string[]")
	.pipe(v => (typeof v === "string" ? v.split(",") : v))
	.to("string[]")
```

**Coercion is a parse.** ArkType never converts a value unless the definition says so, so write the conversion the old library did. `string.numeric.parse`, `string.integer.parse`, `string.date.parse`, `string.json.parse` and `string.url.parse` accept only strings, and accept fewer of them than `Number()` or `new Date()`:

```ts
// z.coerce.number(), which is Number(value) for any input
const Count = type("unknown").pipe(Number).to("number")

// z.coerce.number().int().positive().default(8080) in an object
const Server = type({
	port: type("unknown").pipe(Number).to("number.integer > 0").default(8080)
})

// z.coerce.date(), which is new Date(value) for any input, so null is 1970-01-01
const When = type("unknown")
	.pipe(
		v => new Date(v instanceof Date || typeof v === "string" ? v : Number(v))
	)
	.to("Date")

// stricter, for strings only: rejects " 1", "0x10" and ""
const Page = type("string.numeric.parse")

// z.stringbool() accepts "true", "1", "yes", "on" and their opposites; write the set you need
const Flag = type("'true' | 'false'").pipe(s => s === "true")
```

**Refinements with a path or several errors.** A `.narrow()` returns `true` or calls `ctx.reject()`, which takes a `path` and a full `message`. To report several errors, call `ctx.error()` for each, then return `true`:

```ts
// Zod: .superRefine((d, ctx) => ctx.addIssue({ code: "custom", message: "...", path: ["end"] }))
const Range = type({ start: "number", end: "number" }).narrow(
	(d, ctx) =>
		d.start <= d.end ||
		ctx.reject({ message: "end must not be before start", path: ["end"] })
)
```

**Fallbacks.** ArkType has no `.catch()`. Zod's `.catch(x)` returns `x` for any invalid input, so validate inside a `.pipe()` and return `x` on errors. The default covers a missing key, which `.catch()` also replaces:

```ts
const Count = type("number")

// z.object({ count: z.number().catch(0) })
const Settings = type({
	count: type("unknown")
		.pipe(v => {
			const out = Count(v)
			return out instanceof type.errors ? 0 : out
		})
		.default(0)
})
```

**Discriminated unions are plain unions.** ArkType finds the discriminant itself, so `z.discriminatedUnion("type", [A, B])`, `v.variant("type", [...])` and `Schema.Union(A, B)` are `A.or(B)`, or `"A | B"` in a scope.

**Recursion needs no annotation.** Replace `z.lazy`, `v.lazy`, `Type.Recursive`, `yup.lazy`, `Joi.link` and `Schema.suspend` with a scope, or `this` for a type that refers to itself:

```ts
const Category = type({ name: "string", subcategories: "this[]" })

const types = scope({
	Json: "string | number | boolean | null | Json[] | JsonObject",
	JsonObject: { "[string]": "Json" },
	Filter: { "[string]": "Json | Filter" }
}).export()
```

Delete the hand-written TypeScript type that `z.lazy` needed; `typeof types.Filter.infer` replaces it.

**Composing objects.** `.merge()` replaces keys like Zod's `.extend()`, `v.object({ ...a.entries })` or `Type.Composite`. `.and()` intersects, and throws when a key's types conflict. `.pick()`, `.omit()`, `.partial()`, `.required()` and `.keyof()` keep their names.

**Records with literal keys.** `Record<"a" | "b", T>` must be written as named keys, `{ a: T, b: T }` (add `?` for Zod v3, whose enum-keyed records are partial). An index signature like `"[string]": "number"` applies to every key, including declared ones. Zod's `.catchall(T)` applies only to undeclared keys, so leave the declared ones out of a regex index signature: `z.object({ name: z.string() }).catchall(z.number())` is `type({ name: "string", "[/^(?!name$)/]": "number" })`.

**Brands.** `.brand("UserId")` or `"string#UserId"` infers `Brand<string, "UserId">`, which is not assignable to or from the old library's brand type. Change code that names the old brand type to `typeof UserId.infer`.

**Errors.** Errors are values: `T(data)` returns the data or an `ArkErrors`, and `T.assert(data)` throws. To change a message, `.describe("a strong password")` gives `must be a strong password`, and `.configure({ message: "Choose a stronger password" })` replaces the whole message. Zod's and Valibot's `description` is documentation, but ArkType's `.describe()` is what errors say the value must be, so keep documentation in a comment or `.configure({ title })`.

**Dates and formats.** `z.string().datetime()` rejects offsets and date-only strings unless configured; `string.date.iso` accepts both. In JSON Schema, `format` is an annotation and validates nothing unless the validator, like ajv with `ajv-formats`, checks it; `string.email` always validates.

**Synchronous only.** ArkType doesn't await. Move an async `refine`, Yup `test` or Joi `external` out of the schema and run it after validation.

## Migrating a project

To move a whole project off Zod, or another library below, work through it in this order.

1. **Take stock.** Find every import of the old library (`zod`, `zod/v4`, `zod/mini`) and of packages built on it, like `@hookform/resolvers/zod` or `zod-to-json-schema`, and every use of the schemas, including files that call `.safeParse()` or read `.shape` without importing the library. Run the project's `typecheck` and `test` scripts once, so you know what passes before you start. If `package.json` has no `test` script, step 6 is how you'll check behavior.
2. **Convert each schema in place.** Keep its name, its file and what it takes and returns, so imports and call sites keep working: a `.transform()` stays in the schema as a `.pipe()`, not in its callers. `z.infer<typeof X>` and `z.output` become `typeof X.infer`, and `z.input` becomes `typeof X.inferIn`.
3. **Keep behavior identical.** The migrated schemas should accept, reject and return what the old ones did. These rules are for Zod, and [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ) has them for the other libraries:
   - `z.object()` removes undeclared keys, and so should the migrated objects, even where the code reads only declared keys, since parsed data often reaches a database or a response whole. Call `configure({ onUndeclaredKey: "delete" })` from `arktype/config` in one file, like `src/arktype.config.ts`, and import it first in every file that creates a Type, so it applies whichever file loads first, tests included. If the project [precompiles](https://arktype.io/docs/precompile), also name that file as the build's `config` in [`ark.json`](https://arktype.io/docs/precompile/setup#ark-json), which the CLI and test drivers read as the bundler does. Then `.passthrough()` and `z.looseObject()` become `"+": "ignore"`, and `.strict()` becomes `"+": "reject"`.
   - Without that setting, write `"+": "delete"` in every object instead, nested ones included. `.merge()` takes `"+"` from the object merged in, so write `.merge({ "+": "delete", ... })`; with the global setting, merged objects keep deleting.
   - A union of such objects throws a `ParseError` saying it's indeterminate unless a key tells them apart. Follow [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ) for it, and keep the global setting: `"+": "ignore"` belongs only on the union's branches.
   - `.optional()` also accepts `undefined`, so write `"key?": "T | undefined"`. Before Zod 4.4, any key whose schema accepts `undefined` may be missing, so a `z.unknown()` key is `"key?": "unknown"`; from 4.4, only `.optional()` and defaults let a key be missing, so it stays `key: "unknown"`. Check the version the project installs. In Zod 4, `.default(x).optional()` still fills in `x`, so it's `key: T.default(x)`.
   - `z.any()` is `"unknown.any"`, or `"key?": "unknown.any"` as a key before Zod 4.4. It infers `any` as Zod's did, so refinements that read its properties type-check without casts.
   - Translate coercions and refinements literally, as in [Coercion is a parse](https://arktype.io/docs/migrating#semantics-to-check). `z.coerce.number()` takes any input, `null` included, so its input stays `"unknown"`, in a tool's input schema too. Keywords like `string.numeric.parse` reject inputs Zod accepted, like `" 1"`, so suggest them rather than substituting them. A `.refine()` after a `.transform()` is a `.narrow()` after a `.pipe()`: `.to("number > 0")` would also check the type, and `number` rejects `Infinity` and `NaN`. An object's `.refine()` stays on that object as a `.narrow()`, not in a second schema. Zod 4 runs it even when a key fails a check like `.min()` or `.regex()`, though not when one is missing or of the wrong type, so its issue joins theirs; a narrow runs only once every key is valid.
   - Zod 4.6's `.url()` trims its input, accepts what `URL.canParse` accepts and returns the trimmed string without tabs or line breaks; Zod 4.1's returned it as given. `string.url` checks with `URL.canParse` too but doesn't trim, so where the output is kept, write `type("string").pipe(s => s.trim().replace(/[\t\n\r]/g, "")).to("string.url")`.
   - From Zod 4.5, a string's `.min()`, `.max()` and `.length()` count code points, so an emoji counts once. ArkType's bounds count UTF-16 code units, as `.length` does, so it counts twice. Where text may hold such characters, check the count in a `.narrow()`, as [below](https://arktype.io/docs/migrating#defaults-that-differ).
   - `z.object()` rejects an array, which ArkType accepts as an object whose declared keys are all optional. Where every key is optional, reject arrays with a `.narrow()`, as [below](https://arktype.io/docs/migrating#defaults-that-differ).
   - `string.email` and Zod 4's `z.email()` disagree on some addresses: Zod rejects `a..b@x.co` and `.a@x.co` and accepts `a'b@x.co`, and ArkType does the opposite. Where that matters, keep Zod's pattern as a regex.
   - Keep custom messages. `.min(1, "Name is required")` becomes `type("string >= 1").configure({ message: "Name is required" })`.
4. **Update call sites.**
   - `X.parse(data)` becomes `X.assert(data)`, which throws.
   - `X.safeParse(data)` becomes `const out = X(data)`, then check `out instanceof type.errors`. `parseAsync` and `safeParseAsync` become the same, since ArkType is synchronous.
   - `ZodError` becomes `type.errors`, and `instanceof ZodError` becomes `instanceof type.errors`. Its `issues` keep their `path` and `message`, though a message names its path, like `email must be an email address`, where Zod's says `Invalid email address`. `z.prettifyError(error)` becomes `out.summary`. `X.assert` throws a `TraversalError`, whose `arkErrors` holds them.
   - `error.flatten()` and `z.flattenError(error)` group messages by the first key of their path, so `tags[0]`'s are under `tags`. Group `out.issues` the same way, which also works in a [precompiled](https://arktype.io/docs/precompile) build, where `flatByPath` isn't available:
   - Don't add casts or `any`, not even `as unknown`. A helper typed with `z.ZodTypeAny` or `z.ZodSchema` takes `type.Any`. To keep the output type, use `<T extends type.Any>(schema: T): T["infer"]`, not `type.Any<t>`. A function that builds a schema from another becomes a generic, like `type("<t>", { data: "t" })`.

```ts
// error.flatten() or z.flattenError(error)
const formErrors: string[] = []
const fieldErrors: Record<string, string[]> = {}
for (const issue of out.issues) {
	if (issue.path.length === 0) formErrors.push(issue.message)
	else (fieldErrors[String(issue.path[0])] ??= []).push(issue.message)
}
```

5. **Swap integrations.** Most accept an ArkType type directly, through [Standard Schema](https://arktype.io/docs/standard-schema):

| With Zod | With ArkType |
| - | - |
| `zodResolver(schema)` (react-hook-form) | `standardSchemaResolver(schema)` from `@hookform/resolvers/standard-schema` |
| tRPC `.input(schema)`, `@t3-oss/env-*`, TanStack Form | the same call, given the ArkType type |
| AI SDK 6+ `tool({ inputSchema })`, MCP SDK v2 `registerTool` | the same call, given the ArkType type, which also supplies the JSON Schema |
| AI SDK 5 `tool({ inputSchema })` | `jsonSchema<typeof T.infer>(T.toJsonSchema(), { validate })`, where `validate` returns `{ success: true, value }` or `{ success: false, error }` |
| `zValidator` from `@hono/zod-validator` | `sValidator` from `@hono/standard-validator`, whose hook's `result.error` is the issue array, not `{ issues }`, and a path segment may be `{ key }` |
| `@hono/zod-openapi` | `hono-openapi`: `describeRoute`, `validator` and `resolver` |
| `zod-to-json-schema`, `z.toJSONSchema(schema)` | `schema.toJsonSchema()` |
| `@asteasolutions/zod-to-openapi` | `schema.toJsonSchema({ target: "openapi-3.0" })` for each Schema Object in your OpenAPI document; see below |
| `drizzle-zod` | `drizzle-arktype` |
| a library that accepts only Zod | keep Zod for that call, and say so |

With npm, `@hookform/resolvers`, `@t3-oss/env-core` and other packages that peer on `arktype@^2` make installs fail with `ERESOLVE` until they widen their range. For each package the error names, add an [override](https://arktype.io/docs/upgrading#npm-refuses-packages-that-peer-on-arktype-2) rather than passing `--force` or `--legacy-peer-deps`.

Without casts:

- `toJsonSchema()` returns a `JsonSchema`, the type to give the document's Schema Objects (`import type { JsonSchema } from "arktype"`). Build path and query parameters from an object type's `.props`, which lists each key, whether it's required, and its Type.
- A `fallback` declared apart from the `toJsonSchema()` call is a `ToJsonSchema.FallbackOption` (`import type { ToJsonSchema } from "arktype"`).
- The MCP SDK finds a prompt argument's completer through Zod's `.shape`, so give `argsSchema` one, as below.

```ts
import { completable } from "@modelcontextprotocol/server"
import { type } from "arktype"

const Args = type({ language: "string" })
const argsSchema = {
	"~standard": Args["~standard"],
	shape: {
		language: completable({ "~standard": type("string")["~standard"] }, value =>
			["typescript", "python"].filter(l => l.startsWith(value))
		)
	}
}
```

6. **Compare with the originals while Zod is still installed.** The project's tests check the schemas they use. Check the rest directly, and every schema if there's no `test` script: in a scratch file, import each original from a copy of its file (`git show HEAD:src/schemas.ts > scratch/schemas.zod.ts`) and its conversion, call both on the same inputs and compare which they accept and what they return. Use the project's fixtures or sample data where it has them, plus each case [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ) lists: a missing key, a key present as `undefined`, an undeclared key, a wrong type, an empty string and a value at each bound. Fix each difference in the schema, then delete the scratch files. [How to convert](https://arktype.io/docs/migrating#how-to-convert) shows a check that their types match too.
7. **Swap dependencies.** Remove `zod` and the packages that existed only for it, and add their replacements, with the project's package manager, like `pnpm remove zod` or `npm uninstall zod`. Editing `package.json` by hand leaves the lockfile stale, and some package managers then refuse to run scripts. If `arktype` is already a dependency, keep that version. Don't upgrade another dependency to a new major version, like the MCP SDK to v2, so it takes ArkType; keep Zod for it as the table says. If a dependency requires `zod` as a peer dependency, keep it installed for that dependency and say so.
8. **Verify.** Run the `typecheck` and `test` scripts in `package.json` until both pass; `npx tsc` alone can miss a second tsconfig. Run the `build` script too, if there is one. If there's no `test` script, step 6's comparison is the behavior check, so say what it covered. Search again for imports of the old library, and check that every file importing `arktype`, `.js` files included, imports the config first if it creates a Type. Change a test only where it asserts the old library itself, like a Zod error message or `instanceof ZodError`. Never delete a test, weaken an assertion or change an expected value to match new output. The exception is a snapshot of generated JSON Schema, which ArkType writes in a canonical order: required keys, then optional ones, each sorted, and enum and union members sorted. Reorder such a snapshot only when order is its only difference.
9. **Precompile, if asked.** Set it up as the skill's `references/precompile.md`, or [Precompile setup](https://arktype.io/docs/precompile/setup), says: add `@ark/aot` and the plugin for the bundler, name the config file from step 3 as `config` in `ark.json`, run `npx arktype-precompile --check src` until it accepts every definition, then run the `typecheck`, `test` and `build` scripts again. A library others install doesn't precompile itself: it publishes what `tsc` emits and [opts in](https://arktype.io/docs/precompile/advanced#libraries), so each app's build precompiles it. With `drizzle-arktype`, see [Precompile](https://arktype.io/docs/migrating#precompile) below.
10. **Report** what still behaves differently, if anything, such as error message text, any snapshot you reordered, and any dependency you kept Zod for.

## How to convert

1. Write each schema as the TypeScript type it validates. Most constructs become a string or an object definition; this page's tables map them library by library.
2. Check every row of [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ). A translation that looks right can still accept or return different data.
3. Confirm the types match. While the old schema still exists, a line like this fails to compile until they do:

```ts
type Equals<a, b> =
	[a] extends [b] ?
		[b] extends [a] ?
			true
		:	false
	:	false
const outputMatches: Equals<typeof User.infer, z.output<typeof OldUser>> = true
const inputMatches: Equals<typeof User.inferIn, z.input<typeof OldUser>> = true
```

4. Run both on the same inputs, valid and invalid, and compare which they accept and what they return.

## Adopt incrementally

You don't have to convert a project at once. ArkType and Zod both implement [Standard Schema](https://arktype.io/docs/standard-schema), so each can stand in for the other while you convert:

- **A Zod schema works inside an ArkType definition**, so convert the schemas that use it first and the shared one later:

```ts
import { z } from "zod"

// not converted yet
const Address = z.object({ street: z.string(), city: z.string() })

const User = type({ name: "string", address: Address })
```

- **An ArkType Type works wherever a library accepts Standard Schema**, like tRPC, TanStack Form, Hono's `sValidator` or react-hook-form's `standardSchemaResolver`, so call sites can switch one at a time. [Swap integrations](https://arktype.io/docs/migrating#migrating-a-project) has each.

A Valibot schema embeds the same way. Yup's validates asynchronously, so it can't.

## Precompile

Once your schemas are Types, [add `@ark/aot`](https://arktype.io/docs/intro/setup#add-the-plugin) to your bundler, so each Type ships as a standalone validator with no parser. Your definitions don't change.

A definition that still embeds a Zod or Valibot schema can't be precompiled yet, so the build fails, naming it. Until you've converted it, build with `runtime: "arktype"`, which ships arktype, so what the build can't precompile runs as it did before:

```ts
import { precompile } from "@ark/aot/unplugin"
import { defineConfig } from "vite"

export default defineConfig({
	plugins: [precompile.vite({ runtime: "arktype" })]
})
```

To see what's left, run `npx arktype-precompile --check`, which lists each definition the default build would refuse. See [Dynamic vs Precompiled](https://arktype.io/docs/precompile/dynamic-vs-precompiled).

`drizzle-arktype`, from [Swap integrations](https://arktype.io/docs/migrating#migrating-a-project), creates Types from your tables as the program runs, so the build [runs it on arktype](https://arktype.io/docs/precompile/options#dependencies), shipping the parser. To precompile those Types too, write each one out, with a line that fails to compile if it drifts from the table, like `const matches: Equals<typeof selectTask.infer, typeof tasks.$inferSelect> = true`, `Equals` as in [How to convert](https://arktype.io/docs/migrating#how-to-convert).

## Valibot

| Valibot | ArkType |
| - | - |
| `v.object`, `v.looseObject`, `v.strictObject` | `"+": "delete"`, the default, `"+": "reject"` |
| `v.objectWithRest(entries, rest)` | an index signature, `"[string]": ...` |
| `v.optional(T)`, `v.exactOptional(T)` | `"key?": "T \| undefined"`, `"key?": "T"` |
| `v.optional(T, default)` | `"key": "T = default"`, which applies it only where the key is missing; Valibot also applies it to `undefined`, so see [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ) |
| `v.nullable(T)`, `v.nullish(T)` | `"T \| null"`, `"key?": "T \| null \| undefined"` |
| `v.picklist(["a", "b"])`, `v.enum(E)` | `"'a' \| 'b'"`, `type.valueOf(E)` |
| `v.union`, `v.variant("type", [...])`, `v.intersect` | `A.or(B)`, `A.or(B)`, `A.and(B)` |
| `v.array`, `v.tuple`, `v.tupleWithRest`, `v.record` | `"T[]"`, `[A, B]`, `[A, "...", "B[]"]`, `"Record<string, T>"` |
| `v.lazy` | a scope or `this` |
| `v.pipe(v.string(), v.email(), v.maxLength(255))` | `"string.email <= 255"` |
| `v.minLength`, `v.maxLength`, `v.length`, `v.nonEmpty` | `"string >= n"`, `"string <= n"`, `"string == n"`, `"string > 0"` |
| `v.minValue`, `v.maxValue`, `v.integer`, `v.multipleOf` | `"number >= n"`, `"number <= n"`, `"number.integer"`, `"number % n"` |
| `v.url`, `v.uuid`, `v.isoDateTime`, `v.regex(r)` | `"string.url"`, `"string.uuid"`, `"string.date.iso"`, `/r/` |
| `v.trim()`, `v.toLowerCase()`, `v.toNumber()`, `v.toDate()` | `"string.trim"`, `"string.lower"`, `"string.numeric.parse"`, `"string.date.parse"` |
| `v.check(fn, msg)`, `v.rawCheck` | `.narrow((x, ctx) => fn(x) \|\| ctx.reject({ message: msg }))` |
| `v.forward(v.partialCheck(...), ["key"])` | `.narrow(...)` with `ctx.reject({ path: ["key"] })` |
| `v.transform(fn)` | `.pipe(fn)` |
| `v.brand("Id")` | `.brand("Id")` |
| `v.instance(C)`, `v.date()`, `v.custom(fn)` | `type.instanceOf(C)`, `"Date"`, `type("unknown").narrow(fn)` |
| `v.fallback(T, x)` | none; handle the `ArkErrors` result |
| `v.InferOutput`, `v.InferInput` | `typeof T.infer`, `typeof T.inferIn` |
| `v.parse(S, x)`, `v.safeParse(S, x)` | `T.assert(x)`, `T(x)` |

## TypeBox

TypeBox schemas are JSON Schema, so [JSON Schema](https://arktype.io/docs/migrating#json-schema-and-ajv) also applies.

| TypeBox | ArkType |
| - | - |
| `Type.Object({...})`, `{ additionalProperties: false }` | `type({...})`, `"+": "reject"` |
| `Type.Optional(T)` | `"key?": "T \| undefined"` |
| `Type.String({ minLength, maxLength, pattern })` | `"1 <= string <= 255"`, `/pattern/` |
| `Type.String({ format: "email" })` | `"string.email"` |
| `Type.Number({ minimum, exclusiveMaximum })`, `Type.Integer()` | `"0 <= number < 10"`, `"number.integer"` |
| `Type.Literal`, `Type.Union`, `Type.Enum(E)` | `"'a'"`, `A.or(B)`, `type.valueOf(E)` |
| `Type.Array(T, { minItems })`, `Type.Tuple` | `"T[] >= 1"`, `[A, B]` |
| `Type.Record(Type.String(), T)` | `"Record<string, T>"` |
| `Type.Intersect`, `Type.Composite` | `A.and(B)`, `A.merge(B)` |
| `Type.Partial`, `Type.Pick`, `Type.Omit`, `Type.KeyOf` | `.partial()`, `.pick()`, `.omit()`, `.keyof()` |
| `Type.Recursive(This => ...)` | `this` or a scope |
| `Type.Date()`, `Type.Unknown()`, `Type.Any()` | `"Date"`, `"unknown"`, `"unknown.any"` |
| `Type.Transform(T).Decode(f).Encode(g)` | `codec(T, Out, { decode: f, encode: g })` |
| `Value.Decode(T, x)`, `Value.Encode(T, x)` | `T.assert(x)`, `T.encode.assert(x)` |
| `{ default: x }` with `Value.Default` | `"key": "T = x"` |
| `Static<typeof T>`, `StaticDecode`, `StaticEncode` | `typeof T.infer`, `typeof T.infer`, `typeof T.inferIn` |
| `Value.Check(T, x)`, `Value.Parse`, `TypeCompiler.Compile` | `T.allows(x)`, `T.assert(x)`, nothing to compile |

## Yup

Yup converts values unless `.strict()`, and treats a field as optional unless `.required()`. Translate what the data actually is: a form posting strings needs `"string.numeric.parse"` where Yup's `number()` converted. Like Joi, Yup applies a default to a key present as `undefined`, where `"key": "T = x"` rejects it; [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ) has the pattern that keeps it.

| Yup | ArkType |
| - | - |
| `object({...})`, `.shape({...})` | `type({...})`, `.merge({...})` |
| `string()` (not required) | `"key?": "string \| undefined"` |
| `.required()`, `.defined()`, `.nullable()` | `"key": "string > 0"` for strings, `"key": "T"`, `"T \| null"` |
| `.default(x)` | `"key": "T = x"` |
| `.email()`, `.url()`, `.uuid()`, `.matches(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
| `.min(n)`, `.max(n)`, `.length(n)` on strings, arrays | `"string >= n"`, `"T[] <= n"`, `"string == n"` |
| `.integer()`, `.positive()`, `.moreThan(n)` | `"number.integer"`, `"number > 0"`, `"number > n"` |
| `.trim()`, `.lowercase()` | `"string.trim"`, `"string.lower"` |
| `.oneOf(["a", "b"])` | `"'a' \| 'b'"` |
| `array().of(T)`, `tuple([A, B])` | `T.array()`, `[A, B]` |
| `.test(name, message, fn)` | `.narrow((x, ctx) => fn(x) \|\| ctx.reject({ message }))` |
| `.oneOf([ref("password")])` | a `.narrow()` on the object comparing the keys, which runs only once every key is valid, where Yup reports the mismatch beside other errors |
| `.transform(fn)` | `.pipe(fn)` |
| `.when("other", ...)` | a union of the cases, or a `.narrow()` on the object |
| `lazy` | a scope or `this` |
| `.noUnknown()`, `stripUnknown: true` | `"+": "reject"`, `"+": "delete"` |
| `InferType<typeof S>` | `typeof T.infer` |
| `validateSync(x)`, `isValidSync(x)`, `validate(x)` | `T.assert(x)`, `T.allows(x)`, `T(x)` |

## Joi

Joi rejects undeclared keys, rejects empty strings, and converts strings to numbers, booleans and dates unless `convert: false`. ArkType reads an ISO date-time without an offset as UTC, where Joi reads it in local time. Joi also applies a default to a key present as `undefined`; see [Defaults that differ](https://arktype.io/docs/migrating#defaults-that-differ). It infers no types, so `typeof T.infer` replaces the interfaces written next to Joi schemas.

| Joi | ArkType |
| - | - |
| `Joi.object({...})`, `.unknown(true)` | `type({ "+": "reject", ... })`, `type({...})` |
| `Joi.string()` (optional), `.required()` | `"key?": "string > 0 \| undefined"`, `"key": "string > 0"` |
| `.allow("")`, `.allow(null)` | `"string"`, `"string \| null"` |
| `.valid("a", "b")` | `"'a' \| 'b'"` |
| `.email()`, `.uri()`, `.guid()`, `.pattern(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
| `.min(n)`, `.max(n)`, `.length(n)` | `"string >= n"`, `"string <= n"`, `"string == n"` |
| `Joi.number().integer().positive()` | `"number.integer > 0"` |
| `Joi.number()` reading strings | `"number \| string.numeric.parse"` |
| `Joi.boolean()` reading strings | `type("boolean \| 'true' \| 'false'").pipe(v => v === true \|\| v === "true")` |
| `Joi.date()`, `Joi.date().iso()` | `"Date \| string.date.parse"`, `"string.date.iso.parse"` |
| `Joi.array().items(T)`, `.min(1)` | `T.array()`, `"T[] >= 1"` |
| `.unique()` | `.narrow((a, ctx) => new Set(a).size === a.length \|\| ctx.reject("unique"))` |
| `Joi.alternatives().try(A, B)` | `A.or(B)` |
| `.default(x)` | `"key": "T = x"` |
| `.custom(fn)` | `.narrow()` or `.pipe()` |
| `.messages({...})` | `.configure({ message })` |
| `Joi.link("#id")` | a scope or `this` |
| `.when(...)` | a union of the cases, or a `.narrow()` on the object |
| `schema.validate(x)`, `.attempt(x, schema)` | `T(x)`, `T.assert(x)` |

## Effect Schema

Names are Effect 3's. Effect 4 renames some: `Schema.filter` is `Schema.check`, `Schema.transform` is `Schema.decodeTo` and `Schema.Enums` is `Schema.Enum`.

| Effect Schema | ArkType |
| - | - |
| `Schema.Struct({...})` | `type({ "+": "delete", ... })` |
| `Schema.optional(T)`, `Schema.optionalWith(T, { exact: true })` | `"key?": "T \| undefined"`, `"key?": "T"` |
| `Schema.optionalWith(T, { default: () => x })` | `"key": "T = x"` |
| `Schema.NullOr`, `Schema.NullishOr` | `"T \| null"`, `"T \| null \| undefined"` |
| `Schema.Literal("a", "b")`, `Schema.Enums(E)` | `"'a' \| 'b'"`, `type.valueOf(E)` |
| `Schema.Union(A, B)`, `Schema.TaggedStruct` | `A.or(B)`, an object with a literal `_tag` |
| `Schema.Array`, `Schema.NonEmptyArray`, `Schema.Tuple` | `"T[]"`, `"T[] >= 1"`, `[A, B]` |
| `Schema.Record({ key: Schema.String, value: T })` | `"Record<string, T>"` |
| `Schema.suspend(() => T)` | a scope or `this` |
| `Schema.Int`, `Schema.Positive`, `Schema.between(a, b)` | `"number.integer"`, `"number > 0"`, `"a <= number <= b"` |
| `Schema.minLength`, `Schema.pattern(r)`, `Schema.UUID` | `"string >= n"`, `/r/`, `"string.uuid"` |
| `Schema.NumberFromString`, `Schema.DateFromString` | `"string.numeric.parse"`, `"string.date.parse"` |
| `Schema.Trim`, `Schema.Lowercase`, `Schema.parseJson(T)` | `"string.trim"`, `"string.lower"`, `type("string.json.parse").to(T)` |
| `Schema.filter(fn)` | `.narrow(fn)` |
| `Schema.transform(From, To, { decode, encode })` | `codec(From, To, { decode, encode })` |
| `Schema.brand("Id")` | `.brand("Id")` |
| `Schema.Type<typeof S>`, `Schema.Encoded<typeof S>` | `typeof T.infer`, `typeof T.inferIn` |
| `Schema.decodeUnknownSync`, `decodeUnknownEither` | `T.assert(x)`, `T(x)` |
| `Schema.encodeSync`, `encodeEither` | `T.encode.assert(x)`, `T.encode(x)` |
| `onExcessProperty: "error"` | `"+": "reject"` |

`codec` comes from `arktype/codecs`, and importing it is what makes `.encode` available. A `Schema.Class` becomes a Type plus, if you need methods, your own class constructed from its output.

## JSON Schema and ajv

To keep a schema as JSON, convert it at runtime with `jsonSchemaToType` from `@ark/json-schema`; it accepts exactly what a JSON Schema 2020-12 validator accepts, except that lengths count UTF-16 code units, with `format` as an annotation. To rewrite it as definitions:

| JSON Schema | ArkType |
| - | - |
| `{ type: "string", minLength: 1, maxLength: 255 }` | `"1 <= string <= 255"` |
| `{ type: "string", pattern: "^a" }` | `/^a/` |
| `{ type: "integer", minimum: 0, exclusiveMaximum: 10 }` | `"0 <= number.integer < 10"` |
| `{ multipleOf: 5 }` | `"number % 5"` |
| `{ enum: ["a", "b"] }`, `{ const: "a" }` | `"'a' \| 'b'"`, `"'a'"` |
| `{ type: ["string", "null"] }`, `anyOf`, `oneOf` | `"string \| null"`, `A.or(B)` |
| `allOf` | `A.and(B)` |
| `properties` with `required` | keys, with `?` on those not required |
| `additionalProperties: false`, `additionalProperties: T` | `"+": "reject"`, `"[string]": "T \| A"`, `A` the declared keys' types |
| `patternProperties: { "^x-": T }` | `"[/^x-/]": T` |
| `{ type: "array", items: T, minItems: 1 }` | `"T[] >= 1"` |
| `prefixItems` | `[A, B]` |
| `$defs` with `$ref` | a scope |
| `format: "email"`, `"uuid"`, `"date-time"`, `"uri"` | `"string.email"`, `"string.uuid"`, `"string.date.iso"`, `"string.url"` |
| `default` | `"key": "T = x"` |

ajv options map too: `removeAdditional` is `"+": "delete"`, `useDefaults` is a default in the definition, and `coerceTypes` is a parse keyword like `string.numeric.parse`. `T.toJsonSchema()` converts back.

# Upgrading

> What to change when upgrading from ArkType 2.2, with each breaking change before and after.

Each section is one change since 2.2.9, with code that behaves differently before and after it. The full list of changes, including fixes and new features, is in the CHANGELOGs of [arktype](https://github.com/arktypeio/arktype/blob/main/ark/type/CHANGELOG.md), [@ark/aot](https://github.com/arktypeio/arktype/blob/main/ark/aot/CHANGELOG.md), [arksets](https://github.com/arktypeio/arktype/blob/main/ark/sets/CHANGELOG.md), [@ark/json-schema](https://github.com/arktypeio/arktype/blob/main/ark/json-schema/CHANGELOG.md), [@ark/fast-check](https://github.com/arktypeio/arktype/blob/main/ark/fast-check/CHANGELOG.md), [arkregex](https://github.com/arktypeio/arktype/blob/main/ark/regex/CHANGELOG.md) and [@ark/attest](https://github.com/arktypeio/arktype/blob/main/ark/attest/CHANGELOG.md).

## Checklist

Go down the list. Each question your code answers yes to links to what to change.

- Do you install with npm, beside a package that peers on `arktype@^2`, like `@hookform/resolvers` or `@t3-oss/env-core`? [Override its peer](https://arktype.io/docs/upgrading#npm-refuses-packages-that-peer-on-arktype-2).
- Do you keep a package that depends on arktype 2 itself, like `@ark/json-schema@0.0.13`? [Its Types are Standard Schemas](https://arktype.io/docs/upgrading#packages-that-depend-on-arktype-2).
- Do you ship arktype to a browser without a build step that precompiles? [It's larger](https://arktype.io/docs/upgrading#unprecompiled-arktype-is-larger).
- Do you install `@ark/type`, `@ark/regex` or an `@arktype/*` package? [Rename it](https://arktype.io/docs/upgrading#package-names).
- Do you read `ArkErrors` as an array, like `out[0]`, `out.length`, `out.map()` or `[...out]`? [Read `out.issues`](https://arktype.io/docs/upgrading#arkerrors-is-no-longer-an-array).
- Do you call methods on an error, like `hasCode()`, `toString()` or `instanceof ArkError`? [Errors are plain objects](https://arktype.io/docs/upgrading#errors-are-plain-objects).
- Do you switch on error `code`s, or configure text for `predicate`? See [undeclared](https://arktype.io/docs/upgrading#undeclared-keys-have-the-undeclared-code), [discriminant](https://arktype.io/docs/upgrading#union-misses-have-the-discriminant-code) and [notEqual](https://arktype.io/docs/upgrading#excluded-values-have-the-notequal-codes).
- Do you snapshot or assert error messages, or their order? See [Errors](https://arktype.io/docs/upgrading#errors): messages leave out the value, each failed check is its own error, `assert` throws the errors' summary, dates and union misses print differently, errors follow the order keys are declared, configured messages apply to more errors, and [other messages changed](https://arktype.io/docs/upgrading#other-messages-that-changed).
- Do you show the messages of Standard Schema issues, as a form library does? [Each is its error's `problem`, which leaves out the path](https://arktype.io/docs/upgrading#standard-schema-messages-leave-out-the-path).
- Do you configure an `expected`, `actual` or `message` writer? [Writers take the error](https://arktype.io/docs/upgrading#error-writers-receive-the-error-and-the-locale).
- Do you call `configure()` after a Type is created, or pass a global-only option to a Scope? See [Configuration](https://arktype.io/docs/upgrading#configuration).
- Do you use `number` for data that can be `Infinity`? [Allow it](https://arktype.io/docs/upgrading#number-rejects-infinity).
- Do you write date literals or limits without a time zone, or parse ISO dates without an offset? See [date literals](https://arktype.io/docs/upgrading#date-literals-need-a-time-zone) and [`string.date.iso.parse`](https://arktype.io/docs/upgrading#stringdateisoparse-reads-dates-in-utc).
- Do you use `"@"` or `"[k]?"` as a literal key? [Escape it](https://arktype.io/docs/upgrading#-holds-an-objects-metadata).
- Do you set `clone`, or rely on output being a copy of its input? [Output shares unchanged values](https://arktype.io/docs/upgrading#the-clone-option-is-removed).
- Do you write `"+": "delete"` or `"+": "reject"` and care about key order or symbol keys? See [delete](https://arktype.io/docs/upgrading#-delete-removes-symbol-keys-and-lists-keys-as-declared) and [reject](https://arktype.io/docs/upgrading#-reject-checks-string-keys-only).
- Do you use function defaults, or morphs on defaults? [They run on each call](https://arktype.io/docs/upgrading#defaults-run-each-time-theyre-applied).
- Do you chain two right bounds, like `number < 5 < 6`? [Group them](https://arktype.io/docs/upgrading#a-second-right-bound-throws).
- Do you embed an async Standard Schema, like a Zod schema with an async refinement? [It throws](https://arktype.io/docs/upgrading#standard-schemas-must-validate-synchronously).
- Do you reflect on a Type's own keys or prototype, freeze a Type, compare `type.Record` to the generic, or compare Types written two ways with `===`? [Types are built when they're first read](https://arktype.io/docs/upgrading#types-are-built-when-theyre-first-read).
- Do you store or snapshot `toJsonSchema()`, `.expression` or `.json`, or convert `NaN` or `Infinity` literals to JSON Schema? See [Output](https://arktype.io/docs/upgrading#output).
- Do you rely on what `.required()`, `.map()` or arkregex infer, or reference a Type allowing `undefined` at a key without `exactOptionalPropertyTypes`? See [Inference](https://arktype.io/docs/upgrading#inference) and [ArkRegex](https://arktype.io/docs/upgrading#arkregex).
- Do you use `@ark/schema` without `arktype`? [Import `arksets`](https://arktype.io/docs/upgrading#arkschema).
- Do you import from `@ark/schema`, `@ark/util` or a deep path like `arktype/internal/...`, or read `.internal`? See [@ark/schema](https://arktype.io/docs/upgrading#arkschema), [@ark/util](https://arktype.io/docs/upgrading#arkutil) and [Deep imports](https://arktype.io/docs/upgrading#deep-imports).
- Do you use `@ark/json-schema`, `@ark/fast-check` or attest, or run attest on TypeScript 7? See their sections below.

## Installing

### npm refuses packages that peer on arktype 2

Some packages list `arktype@^2` as a peer dependency, like `@hookform/resolvers`, `@t3-oss/env-core`, `@standard-community/standard-json`, `xsschema`, `@regle/schemas`, `@typeschema/arktype`, `@hono/arktype-validator` and `@arkenv/core`. npm won't install one beside a later major version of `arktype`, even where its peer is optional: `npm install arktype@latest` only warns, but each install after it, `npm ci` included, fails with `ERESOLVE`. Until a package widens its range, point its peer at your `arktype` in `package.json`, one entry for each package the error names:

```json
{
	"overrides": {
		"@hookform/resolvers": { "arktype": "$arktype" },
		"@t3-oss/env-core": { "arktype": "$arktype" }
	}
}
```

`$arktype` is the version your `dependencies` list, so update `arktype` there, then run `npm install`. An override of `arktype` alone, `{ "arktype": "$arktype" }`, would also hand your version to packages that depend on arktype 2 itself rather than peering on it.

pnpm installs with an `unmet peer` warning, which `peerDependencyRules` in `pnpm-workspace.yaml` silences, and bun doesn't warn:

```yaml
peerDependencyRules:
  allowedVersions:
    arktype: "3"
```

### Packages that depend on arktype 2

A package that depends on arktype 2 itself, like `@ark/json-schema@0.0.13`, installs its own copy. A Type it returns works in a definition, `.pipe()` or `.to()` as a [Standard Schema](https://arktype.io/docs/standard-schema), validating with its own copy, and `toJsonSchema()` writes what that copy's converter does, throwing where that can't stand for the Type, as for one with a morph. A module or Generic from it used in a Scope, or a Type passed to `type.schema()`, throws a `ParseError`: upgrade the package, or override its `arktype`.

## Bundle size

### Unprecompiled arktype is larger

`import { type } from "arktype"` bundles more than it did, mostly for copy-on-write transforms, cyclic data, errors and their English text, and the set algebra that reduces unions and intersections. [Speed and size](https://arktype.io/docs/precompile#speed-and-size) compares the builds.

To ship less than before, [precompile](https://arktype.io/docs/intro/setup#add-the-plugin). Each Type becomes a standalone validator on `arktype/runtime`, so arktype's parser never ships. Your definitions don't change.

## Errors

### ArkErrors is no longer an array

`ArkErrors` was an `Array` subclass. It's now a plain class whose `issues` is a plain array with an error for each failed check. Indexing, iteration, `length` and array methods move to `issues`:

```ts
const out = type({ name: "string" })({ name: 5 })

if (out instanceof type.errors) {
	// before: out[0], out.map(e => e.message), for (const e of out), out.length
	out.issues[0]
	out.issues.map(e => e.message)
	for (const error of out.issues) console.log(error.message)
	out.issues.length
}
```

`Array.isArray(out)` is now `false`, and `[].concat(out)` nests the errors instead of spreading them, so pass `out.issues`. A [Standard Schema](https://arktype.io/docs/standard-schema) failure is no longer the `ArkErrors`, but `{ issues }`, as [below](https://arktype.io/docs/upgrading#standard-schema-messages-leave-out-the-path).

`ArkErrors` keeps `issues`, `count`, `summary`, `throw()`, `toJSON()`, `toString()` and `toLocaleString(locale)`. `message` and `toTraversalError()` are gone: read `summary`, and call `throw()`. `byPath`, `flatByPath`, `flatProblemsByPath` and `byAncestorPath` are functions `arktype` exports:

```ts
import { flatProblemsByPath, type } from "arktype"

const out = type({ name: "string" })({ name: 5 })

if (out instanceof type.errors) {
	// before: out.flatProblemsByPath
	flatProblemsByPath(out)
}
```

A [precompiled](https://arktype.io/docs/precompile/validators#errors) build's `arktype/runtime` doesn't export them, and its errors have no `propString` or `problem`, so there group `out.issues` by `issue.path` instead.

A callback adds an error with `ctx.error` or `ctx.reject` rather than `ctx.errors.add`.

### Standard Schema messages leave out the path

A [Standard Schema](https://arktype.io/docs/standard-schema) failure is `{ issues }`, a plain array with a copy of each error whose `message` is the error's `problem`, which leaves its path out, since a consumer like a form library shows it beside the field or prints the path before it:

```ts
const T = type({ name: "string > 1" })

// [{ message: "must be at least length 2", path: ["name"], ... }]
// before: "name must be at least length 2 (was 1)"
T["~standard"].validate({ name: "x" })
```

A union's or an intersection's `problem` writes the path of each error it lists from its own, like `b must be a string (was missing) or c must be a number (was missing)`, while its `message` still writes them whole. A configured `message` no longer reaches the issues, so move a `message` writer that customized them to [`problem`](https://arktype.io/docs/configuration#problem).

Update snapshots of those messages, and read `summary` from the errors calling the Type returns for one line naming each path.

### Errors are plain objects

The errors in `issues` are plain objects without getters or methods, holding the keys their JSON had plus `propString`, before `expected`, so serialized issues, like the `errors` `@hono/arktype-validator` responds with, include it. `ArkError` is exported only as a type, which comparing `code` narrows as `hasCode` did, and `messageIn` writes one in a locale:

```ts
import { messageIn, type } from "arktype"
import { de } from "arktype/locales/de"

const out = type({ n: "number % 2" })({ n: 1 })

if (out instanceof type.errors) {
	for (const error of out.issues) {
		// before: error.hasCode("divisor")
		if (error.code === "divisor") console.log(error.rule)
		// before: error.toLocaleString(de)
		messageIn(error, de)
	}
}
```

`hasCode`, `flat`, `throw`, `toString`, `toJSON` and `toLocaleString` are gone from errors, so `error instanceof ArkError` is false and `` `${error}` `` is `[object Object]`. `path` is a plain array. An error's text is written when its `ArkErrors`' issues are first read, so a configured writer is called once per error. A Type that calls no narrow or morph may also find the issues themselves at that read, so [read them before the data you validated changes](https://arktype.io/docs/errors#arkerrors).

### Messages leave out the value

A message no longer says what the value was. An error's `actual` still describes its data, and a `problem` or `message` you configure still reads it, but only a missing key's message writes it, so a message ends with what was expected, and a missing key still says it was missing. A message no longer grows with the data, nothing the data holds reaches a log through it, and a Type's messages read as a [precompiled validator's](https://arktype.io/docs/precompile/validators#errors) do:

```ts
// ArkErrors: must be "a" or "b", before: must be "a" or "b" (was {"x":1})
type("'a' | 'b'")({ x: 1 })

// ArkErrors: name must be a string, before: name must be a string (was a number)
type({ name: "string" })({ name: 5 })

// ArkErrors: name must be a string (was missing), as before
type({ name: "string" })({})
```

A key a union lists doesn't say it was missing: `a must be a string or b must be a number`. To print the value, configure [`actual`](https://arktype.io/docs/configuration#actual):

```ts
// ArkErrors: must be at most 100 (was 101)
type("number <= 100").configure({ actual: data => `${data}` })(101)
```

A union whose every branch rejects the value by its type, class or literal, like `Date | RegExp`, is one error with no `errors` of its own: `must be a Date or a RegExp`.

### Each failed check is its own error

Checks failing at one path were one `intersection` error listing them. Each is now its own error, in the order it failed:

```ts
// ArkErrors: must be matched by ^a
//            must be non-empty
// before: ("") must be...
//   ◦ matched by ^a
//   ◦ non-empty
type("string > 0 & /^a/")("")
```

`issues.length` counts failed checks, so count paths with `flatByPath`, which lists each error at a path, or `byPath`, which keeps the first. Code switching on the `intersection` code, or reading an error's `errors` for an intersection's, reads each error instead.

### assert throws the errors' summary

The `TraversalError` `assert` and `throw()` raise has the errors' `summary` as its `message`, where several errors were written on lines starting with `•` after an empty first line:

```ts
// throws TraversalError: a must be a string (was missing)
// b must be a number (was missing)
// before: TraversalError:
//   • a must be a string (was missing)
//   • b must be a number (was missing)
type({ a: "string", b: "number" }).assert({})
```

### Paths don't start with "value at"

A message whose path started with a bracket began with `value at`. It no longer does, and a symbol key is written as `String` writes it:

```ts
// ArkErrors: [0] must be a string, before: value at [0] must be a string (was a number)
type("string[]")([5])
```

### Undeclared keys have the undeclared code

A key that `"+": "reject"` disallows was a `predicate` error. Its code is now `undeclared`, and its `data` is the key's value rather than the object:

```ts
const T = type({ "+": "reject", a: "string" })

const out = T({ a: "x", b: 1 })

if (out instanceof type.errors) {
	out.issues[0].code // "undeclared", before: "predicate"
	out.issues[0].data // 1, before: { a: "x", b: 1 }
}
```

Configure its text under `undeclared` instead of `predicate`.

### Union misses have the discriminant code

A value that matches no branch of a union ArkType checks by its type or by a literal value, like `number | null`, `"a" | "b" | "c"` or objects with a discriminant key, was a `predicate` error, and one of two literals, like `boolean`, was a `union` error. Its code is now `discriminant`, and its `data` is the discriminating value:

```ts
const out = type("number | null")("x")

if (out instanceof type.errors) {
	out.issues[0].code // "discriminant", before: "predicate"
}
```

A described union's miss is at the union's own path, with the union's value as its `data`. A union reports `union` rather than `discriminant` where its discriminant can't tell the branches apart: for data that can't hold it, like `5` for a union of objects, for data matching none of its values when some branches don't have its key, and for a miss of a union discriminated by its value whose branch is described.

Configure its text under `discriminant` instead of `predicate`.

Where every object a union discriminated by type expects is an array, its `cases` holds `"Array"` in place of `"object"`, and its message says `an array`:

```ts
// ArkErrors: must be a string or an array
// before: must be a string or an object (was a number)
type("string | string[]")(5)
```

A `switch` over `cases` must handle `"Array"`.

### Excluded values have the notEqual codes

`!=` excludes one value from a range, like `number != 0`, and unions of ranges one value apart reduce to it. Its errors have the codes `notEqual` and `notEqualLength`, so with `undeclared` and `discriminant`, an exhaustive `switch` over `ArkErrorCode`, or a `Record<ArkErrorCode, ...>`, must handle four new codes:

```ts
// ArkErrors: must be other than 0
type("number != 0")(0)
```

### Unions report each branch their discriminant can't rule out

A discriminated union whose discriminant can't place the data, because the data can't hold it, or matches none of its values while some branches don't have its key, reports as an undiscriminated union does, listing each branch's error. Each path a union lists reads as its own error would:

```ts
// ArkErrors: must be an object
// before: kind must be "circle" or "square" (was missing)
type({ kind: "'circle'", r: "number" }).or({
	kind: "'square'",
	side: "number"
})(5)

// ArkErrors: [0] must be a number or [1] must be a string
// before: value at [0] must be a number (was a string) or [1] must be a string (was a number)
type("number[] | string[]")(["a", 1])
```

Objects alike but for one key's value are now one object (see [Output](https://arktype.io/docs/upgrading#output)), so data they reject is reported as any object's is, each failing key on its own, and a message configured on the union no longer replaces the error at that key.

### Errors follow the order keys are declared

An object's errors are reported in the order its definition declares its keys, where they were required keys first, then optional ones, each sorted. On a failed call, each morph whose input is valid runs as it's reached, so its errors are in that order too:

```ts
import { firstIssue, type } from "arktype"

const User = type({ name: "string", age: "number", "nick?": "string" })

const out = User({ nick: 0 })

if (out instanceof type.errors) {
	// "name must be a string (was missing)"
	// before: "age must be a number (was missing)"
	firstIssue(out).message
}
```

Declared keys are still checked before an index signature's and undeclared keys, which follow the data's order.

### Configured messages apply to more errors

A `message` configured on a pipe applies to errors validating its output, and a union whose failing branches were all configured with one `message` reports it:

```ts
const Port = type("string.numeric.parse | number")
	.to("0 < number <= 65535")
	.configure({ message: "Enter a port number." })

// ArkErrors: Enter a port number.
// before: must be at most 65535 (was 99999)
Port("99999")

const message = "Enter an email or a phone number"
const Contact = type("string.email")
	.configure({ message })
	.or(type(/^\d{7,}$/).configure({ message }))

// ArkErrors: Enter an email or a phone number
// before: what each branch expected
Contact("x")
```

`Port.out` keeps its own errors. Each constraint an intersection fails is [its own error](https://arktype.io/docs/upgrading#each-failed-check-is-its-own-error), with its own message, so `type("string.email > 0").configure({ message: "Email is not valid" })("")` says `Email is not valid` twice.

### Error writers receive the error and the locale

An `expected` writer receives the error rather than its context, an `actual` writer receives `(data, error, locale)`, and every writer receives the [locale](https://arktype.io/docs/i18n) last. In an `expected` writer, `meta` may be `undefined`, since an error from `ctx.reject` has none:

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

configure({
	predicate: {
		// before: ctx => ctx.meta.title!
		expected: error => error.meta?.title ?? "valid"
	}
})
```

A writer's argument no longer has `toJSON`, `toString` or the text getters that could read the text it writes.

### pipe.try errors reference the morph

An error from a `pipe.try` morph that threw has the function as `morph` and what it threw as `cause`. Before, it had them as `predicate` and its own `actual`. Its `code` is still `predicate`, and its message is unchanged:

```ts
const Parse = type("string").pipe.try((s): object => JSON.parse(s))

const out = Parse("{")

if (out instanceof type.errors) {
	const error = out.issues[0]
	// error.morph is the function, before: error.predicate
	// error.cause is the SyntaxError it threw, before: error.actual
}
```

### Keyword parse errors are data

The errors `string.integer.parse`, `string.date.parse`, `string.url.parse`, `string.json`, `string.json.parse` and `string.regex` raise while parsing carry `meta.keyword`, a `description` and what was thrown as `cause`, instead of their own English `expected` text. Their messages are unchanged, and `predicate` config now applies to them:

```ts
const out = type("string.json.parse")("{")

if (out instanceof type.errors) {
	const error = out.issues[0]
	// error.meta is { keyword: "string.json.parse" }
	// error.cause is the SyntaxError JSON.parse threw
}
```

### assert throws when a root morph fails

When a Type's root is a morph that returns `ArkErrors`, `.assert` throws instead of returning them, and a configured `onFail` is called:

```ts
const N = type("number")
const T = type("string").pipe(s => N(s))

// before: returned ArkErrors
// throws TraversalError: must be a number
T.assert("x")
```

### Dates are described in UTC

Dates in descriptions and error messages are written in UTC instead of local time. A date at midnight is written as its calendar date:

```ts
const T = type("Date < d'2000-01-01T12:30:00Z'")

// ArkErrors: must be January 1, 2000, 12:29:59.999 PM UTC or earlier
// before, in New York: must be 7:29:59.999 AM, January 1, 2000 or earlier
T(new Date("2001-06-01"))
```

### Other messages that changed

Each was wrong or unclear, but a snapshot or message assertion may hold it:

- `string.regex`: `must be a regex pattern (SyntaxError: Invalid regular expression: /(/: Unterminated group)`, before: the bare `SyntaxError: ...`.
- `{ foo: string } | { foo: number } | { foo: Function }` given `{ foo: null }`: `foo must be a number, a string or an object`, before: `foo must be an object, a number or a string (was null)`.
- A key that must be `never`: `files must be never`, before: `never`.
- A described union: `must be a shape`, where it listed its cases or its branches' errors.
- An object `===` unit: `must be {}`, before: `must be reference equal to {} (serialized to the same value)`.
- A value inside `object.json` that JSON can't hold: `a must be a number, a string, an object, boolean or null`, before: `a must be an object (was a bigint)`.
- `number.safe` and other ranges given `Infinity`: `must be a number`, before: their range error.
- An arktype Type embedded through `~standard`: `user.age must be an integer`, before: `user.age age must be ...`.
- Keyword descriptions: `string.url` is `a URL string` (before: `a string and a URL string`), `string.creditCard` is `a credit card number` (before: repeated), and `string.lower` and `string.upper`'s outputs are `lowercase` and `uppercase` (before: `only lowercase letters`).
- A `ToJsonSchemaError` starts with a sentence: `Can't convert "date" at user.createdAt to JSON Schema. Configure fallback.date to write it:`, then the context it printed before.
- A default a morph's input rejects throws `ParseError: Default for flag must be "false" or "true"`, written from the input, where it threw `TraversalError: must be boolean (was false)` from the morph's description.
- `ParseError`s for an indeterminate union or intersection of morphs end with a line saying how to fix it, and one for an intersection adding a key the other side deletes or rejects names that key on two more lines.
- `ParseError`s name what they reject: `Token '>=' requires a right operand` for `"number >="` (before: `Expected an expression`), the narrow in `Intersection of "a" | "b" and isC results in an unsatisfiable type` (before: `and unknown`), and only the conflicting elements of an unsatisfiable tuple intersection.

## Validation

### "@" holds an object's metadata

An object definition's `"@"` key is its description or meta object, as `"@"` is in a tuple expression. It was an ordinary key. Escape it as `"\\@"` to keep the key:

```ts
// ArkErrors: must be a user
type({ "@": "a user", name: "string" })(5)

// Type<{ "@": string }>
const At = type({ "\\@": "string" })
```

### Date literals need a time zone

A date literal, or a string passed as a date limit, must be the same instant on every machine: an ISO date (UTC) like `2025-01-01`, an ISO date-time with `Z` or an offset, or epoch milliseconds. A date-time without an offset or a non-ISO string was read in the local time zone, and now throws a `ParseError`:

```ts
// throws ParseError: Date literal '2025-01-01T12:00' must be an ISO date like 2025-01-01, an ISO date-time with Z or an offset like 2025-01-01T12:00Z, or epoch milliseconds
// before: noon in the machine's time zone
type("Date > d'2025-01-01T12:00'")

// unchanged
type("Date > d'2025-01-01'")
type("Date > d'2025-01-01T12:00Z'")
```

### string.date.iso.parse reads dates in UTC

`string.date.iso.parse` reads an ISO date or date-time without an offset as UTC, so one string is one instant on every machine, and a date that doesn't exist fails rather than rolling over. `string.date.parse` and `string.date` read the strings `string.date.iso` accepts the same way:

```ts
const parse = type("string.date.iso.parse")

// 2025-01-01T12:00:00.000Z
// before, in New York: 2025-01-01T17:00:00.000Z
parse("2025-01-01T12:00")

// ArkErrors: must be an ISO 8601 date or date-time
// before: 2025-03-01T00:00:00.000Z
parse("2025-02-29")
```

### Merging an array throws

`.merge`, `type.merge` and `Merge` extend an object, so an array, a tuple or another class's instance on either side throws a `ParseError`, where merging an array gave an object:

```ts
// throws ParseError: merge operand must resolve to an object literal type (was string[])
type({ a: "string" }).merge("string[]")
```

Spread the array's Type into a tuple, or merge objects only.

### A second right bound throws

A range takes at most one right bound, so a second throws a `ParseError`, as its type already failed:

```ts
// throws ParseError: Expression number must have at most one right bound
// before: number < 5
type("number < 5 < 6")

// intersect a second comparator
type("0 < number < 10 & number != 5")
```

### number rejects Infinity

`number` rejects `Infinity` and `-Infinity`, as it already rejected `NaN`:

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

Allow them everywhere with `configure({ numberAllowsInfinity: true })`, or in one Type with the `number.Infinity` and `number.NegativeInfinity` keywords:

```ts
const T = type("number | number.Infinity | number.NegativeInfinity")
```

### object.json accepts only plain objects and arrays

`object.json` rejects an object whose prototype isn't `Object.prototype` or `null`, unless it's an array, so a `Map`, `Set`, `Date`, function or class instance, which `JSON.stringify` doesn't write as itself, fails anywhere in the data:

```ts
// ArkErrors: at must be a plain object or array
// before: { at: Date }
type("object.json")({ at: new Date() })
```

### string.numeric accepts exponents

`string.numeric` and `string.numeric.parse` accept an exponent, as `Number()` does:

```ts
// 100000, before: ArkErrors: must be a well-formed numeric string (was "1e5")
type("string.numeric.parse")("1e5")
```

To keep rejecting them, intersect a pattern: `"string.numeric & /^[^eE]*$/"`.

### .and checks props against index signatures

`.and` checks each prop against the other side's index signatures as an object literal does, so a required prop they exclude throws a `ParseError`, and an optional one becomes `never`:

```ts
// throws ParseError: Intersection at a of string and number results in an unsatisfiable type
// before: { [string]: number, a: string }
type({ a: "string" }).and({ "[string]": "number" })
```

Widen the index signature's value to include the prop's, like `"[string]": "string | number"`.

### Integer keys past an array's last index are undeclared

An integer key from 4294967295 up can't be an array index, so `"+": "reject"` rejects it and `"+": "delete"` deletes it:

```ts
const T = type("string[]").onUndeclaredKey("reject")

// ArkErrors: ["4294967295"] must be removed, before: valid
T(Object.assign(["a"], { 4294967295: "b" }))
```

### Standard Schemas must validate synchronously

A Standard Schema in a definition whose `validate` returns a Promise, like a Zod schema with an async refinement, throws when it's validated, where it gave `undefined`:

```ts
import { z } from "zod"

const T = type({ name: z.string().refine(async s => s.length > 1) })

// throws: Standard Schema definitions must validate synchronously (zod returned a Promise)
// before: { name: undefined }
T({ name: "x" })
```

### .allows is false when a narrow adds an error

A narrow that adds an error through `ctx` and returns a truthy value failed validation, but `.allows` returned `true`:

```ts
const T = type("number").narrow((n, ctx) => n > 0 || !!ctx.error("positive"))

T.allows(-1) // false, before: true
```

### .extends ignores meta

`.extends` and `.subsumes` compare Types without their meta, so a described Type extends its undescribed self. `.equals` still compares meta:

```ts
type("string | number").describe("a key").extends("string | number") // true, before: false
```

### Optional index signatures throw

A key like `"[k]?"` was the literal key `"[k]"`, made optional. It now throws a `ParseError`, since it reads as an optional index signature. Escape its `[` to keep the literal key:

```ts
// throws ParseError: Index signature [k] can't be optional. Escape its '[' with a backslash for an optional key named '[k]'
type({ "[k]?": "string" })
// TypeScript: Index signature [k] can't be optional. Escape its '[' with a backslash for an optional key named '[k]'

// Type<{ "[k]"?: string }>
type({ "\\[k]?": "string" })
```

### The clone option is removed

Transforming no longer clones the input first. Output shares every value nothing transformed with the input, and a morph receives the validated value itself, so a morph that mutates its argument mutates your data. Remove `clone` from your config.

```ts
const T = type({ a: "string.trim", b: { c: "string" } })
const input = { a: " x ", b: { c: "y" } }

T.assert(input).b === input.b // true, before: false
```

### "+": "delete" removes symbol keys and lists keys as declared

`"+": "delete"` also removes undeclared symbol keys, and its output lists keys in the order the definition declares them, as Zod does, rather than the input's order:

```ts
const T = type({ "+": "delete", b: "string", a: "string" })

T({ a: "1", z: 0, b: "2" }) // { b: "2", a: "1" }, before: { a: "1", b: "2" }
```

### "+": "reject" checks string keys only

`"+": "reject"` allows undeclared symbol keys. Reject types that differ only by a symbol key now overlap, so a union of them with a morph is indeterminate:

```ts
const T = type({ "+": "reject", a: "string" })

// valid, before: ArkErrors: value at [Symbol(s)] must be removed
T({ a: "x", [Symbol("s")]: 1 })
```

### Defaults run each time they're applied

A function default is called each time the default is applied, and its result is validated like input at that key, where it was called once when the Type was defined. A morph on a primitive default runs on each call too:

```ts
let calls = 0

const T = type({ count: ["number", "=", () => ++calls] })

// calls is 0, before: 1, from checking the default when T was defined
T({}) // { count: 1 }
```

### Smaller fixes that change results

Each was a bug, but code may depend on it:

- `string[] & number[]` is `[]`, where it allowed any array: `type("string[] & number[]").expression` is `[]`, before: `unknown[]`.
- Intersecting an object that rejects or deletes undeclared keys with an index signature keeps its optional keys optional: `type({ "+": "reject", "a?": "number" }).and({ "[string]": "number" })` accepts `{}`, before: rejected it.
- With `jitless`, a `g` or `y` pattern checks from the start of the string every time, where the same input alternated between valid and invalid.
- An optional key in an intersection allows `undefined` only where both sides do, so a Scope configured with `exactOptionalPropertyTypes: false` no longer loosens a Type from one that isn't.
- With `exactOptionalPropertyTypes: false`, a defaulted key given `undefined` gets the default, before: kept `undefined`.
- A tuple expression's `:` after a morph throws `ParseError: Predicate operand must be unknown (was a morph)`, where it threw a TypeError.
- `Exclude` and `Extract` over a definition still being defined throw `ParseError: Extract can't filter a type still being defined`.
- `type(["string", "toString"])` throws that `'toString'` is unresolvable, where it threw an internal TypeError.

### Shallow cycles throw

An alias that resolves to itself without passing through an object, array or morph accepted every value. It now throws a `ParseError`:

```ts
// throws ParseError: Alias 'a' has a shallow resolution cycle: a->a
scope({ a: "a" }).export()
// TypeScript: Alias 'a' has a shallow resolution cycle: a->a
```

## Configuration

### Configure 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 `configure` throws after that, where it used to apply to scopes created later but not to `type` or keywords. Call it in a file of its own, and import that file before anything creates a Type:

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

configure({ onUndeclaredKey: "delete" })
```

```ts
import "./config.ts"
import { type } from "arktype"
```

### Global-only options throw in a Scope

`onUndeclaredKey`, `numberAllowsNaN`, `numberAllowsInfinity`, `dateAllowsInvalid`, `keywords` and `locale` can only be set with `configure()`. A Scope's type already rejected them, but a cast config passing one was honored for `onUndeclaredKey` and ignored for the rest. Each now throws:

```ts
// throws ParseError: numberAllowsInfinity can only be configured globally, with configure()
// before: ignored
scope({}, { numberAllowsInfinity: true } as never)
```

### onUndeclaredKey: "delete" rejects overlapping object unions

With `onUndeclaredKey: "delete"` configured, a union of objects whose inputs overlap throws a `ParseError`, as it already did with `"+": "delete"` in each object. Before, data both allowed came out as whichever branch sorted first:

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

configure({ onUndeclaredKey: "delete" })
```

```ts
// throws ParseError: An unordered union of a type including a morph and a type with overlapping input is indeterminate
// before: { uri: "u", blob: "b" } for { uri: "u", text: "t", blob: "b" }
type({ uri: "string", text: "string" }).or({ uri: "string", blob: "string" })
```

Give the branches a key that tells them apart, like a literal `kind`, or delete outside the union.

### meta.keyword is reserved

Built-in keywords set `meta.keyword` on the constraints they add, so a [locale](https://arktype.io/docs/i18n) can find their phrase. Rename your own meta named `keyword`. A keyword's meta in `.json` holds it beside its description:

```ts
// { domain: "string", pattern: [{ rule: "...", meta: { description: "an email address", keyword: "string.email", format: "email" } }], ... }
// before: the pattern's meta was its description, "an email address"
type("string.email").json
```

## Introspection

### Types are built when they're first read

`type()` builds a definition it can prove won't throw when the Type is first read, by a call or any member, rather than when it's defined. Until then, reflecting on the Type itself sees a function:

```ts
const User = type({ name: "string" })

Object.keys(User) // [], before: its node's keys
User.expression // "{ name: string }", which builds it
Object.keys(User) // its node's keys
```

- `Object.keys()`, `Object.hasOwn()`, `Object.getOwnPropertyDescriptor()`, `Reflect.ownKeys()`, `for...in` and spreading see only a function's `length` and `name`, and `key in User` answers for a key the Type holds itself as it would for `type.object`.
- `Object.getPrototypeOf()` returns a prototype every unread Type shares. `instanceof` builds the Type, so it answers as before.
- `Object.freeze()`, `Object.seal()` and `Object.preventExtensions()` make the first read throw a `TypeError`, where they made the Type throw once it compiled.
- `type.Record` is a function that calls and reads through to the `Record` generic, so `type.Record === type.keywords.Record` is `false`.
- Two spellings of one Type can be two equal Types, depending on which is created and read first, as with `type("string")` and `type.keywords.string.root`, or `type("'b'")` and `type('"b"')`, and `/a/` and `"string & /a/"` always are. Definitions written alike are still one Type, as are union order, `.array()` and `[]`, and `type.string` and `"string"`.

## Output

These change what `toJsonSchema()`, `.expression` and `.json` return, which matters if you store or snapshot them.

- `jsonSchema` meta is the Type's JSON Schema, replacing what its constraints imply, where it was written into the schema as an ordinary `jsonSchema` key. See [Your own schema](https://arktype.io/docs/json-schema/to-json-schema#your-own-schema).

- Unions of ranges that overlap, meet or leave out one value, and of objects alike but for one key's value, are one range or object: `1 < number < 10 | 10 <= number < 100` is `1 < number < 100`, `number < 0 | number > 0` is `number != 0`, and `{ kind: "a", x: string } | { kind: "b", x: string }` is `{ kind: "a" | "b", x: string }`.

- `string.date.iso` writes `format: "date-time"` beside its `pattern`, whose groups no longer capture, and a format keyword constrained further keeps its `format`: `"string.email < 255"` writes `format: "email"`, before: none. The [CHANGELOG](https://github.com/arktypeio/arktype/blob/main/ark/type/CHANGELOG.md#write-string-keywords-formats-in-json-schema) lists each keyword's.

- A union of literals with configured meta becomes `enum`: `type("'a' | 'b'").configure({ title: "Letter" }).toJsonSchema()` is `{ type: "string", enum: ["a", "b"], title: "Letter" }` instead of an `anyOf` of `const`s.

- A literal's JSON Schema has its `type` beside its `const` or `enum`: `'a' | 'b'` is `{ type: "string", enum: ["a", "b"] }`, and `'a' | 'b' | null` is `{ anyOf: [{ type: "string", enum: ["a", "b"] }, { type: "null" }] }`.

- A cyclic Type's `$defs` hold only its cyclic aliases, named by the alias, like `user`, with everything else inline, where every object, array and union was a def named like `user1` or `intersection1`.

- A string index signature beside declared keys becomes `patternProperties: { "": ... }` instead of `additionalProperties`.

- `toJsonSchema()` throws for a regex flag JSON Schema can't express, instead of leaving it out: `type(/^a/i).toJsonSchema()` throws (code `patternFlags`), before: `{ type: "string", pattern: "^a" }`, which rejects `"A"`.

- `toJsonSchema()` throws for an index signature key it can't express, instead of leaving out the index signature: `type({ "[string <= 3]": "number" }).toJsonSchema()` throws (code `indexKey`), before: `{ type: "object" }`. See [JSON Schema](https://arktype.io/docs/json-schema/to-json-schema#how-types-map) for the keys it can write.

- `toJsonSchema()` throws for a `NaN`, `Infinity` or `-Infinity` literal, like `number.NaN` or `number.Infinity`, since JSON can't hold one, where it wrote `const: Infinity`, which serializes as `null`. [Handle the `unit` code](https://arktype.io/docs/json-schema/to-json-schema#fallback-codes), e.g. `unit: ctx => (typeof ctx.unit === "number" ? { type: "number" } : ctx.base)`.

- `toJsonSchema()` throws for `object.json` and the Types it's part of, like `string.json.parse`'s output, since its check that an object is plain is a `predicate`. [Handle that code](https://arktype.io/docs/json-schema/to-json-schema#fallback-codes) to write it as before.

- `toJsonSchema()` throws a `ParseError` for a `target` other than `"draft-2020-12"`, `"draft-07"` or `"openapi-3.0"`, where it wrote draft 2020-12: `type("string").toJsonSchema({ target: "draft-04" })`, before: `{ type: "string" }`.

- Expressions keep length bounds and protos beside a structure: `type("number[] > 1").expression` is `number[] >= 2`, before: `number[]`.

- Expressions parse back: `type("1 <= number <= 5").expression` is `1 <= number <= 5`, before: `number <= 5 & >= 1`, and a Date is an ISO literal, `Date >= d'2000-01-01T00:00:00.000Z'`, before: its `toString()` in the local time zone.

- A cyclic Type's `json` names an alias it references by its registered resolution, like `"$ark.tree2"`, before: `"$tree"`, and its `expression` prints another alias of its cycle by name: `{ b: $b }`, before: `{ b: { a?: $a } }`. A `this` reference prints as `this`, before: an id like `type64`.

- In an `expression` or `description`, a nested Type whose own string would be longer than 1000 characters prints as `...`, as `list<...>` already did. Before, it was written in full at each reference.

- `object.json`'s `expression` and `description` are `{ [string]: $jsonData }`, before: its alias's branches.

- Functions and symbols print by name: `{ Symbol(tag): string }`, before: `{ $ark.tag: string }`. In `json`, a repeated name is counted as `isLong$1`, before: `isLong1`, and keyword morphs are named by what they do, like `$ark.trimString`, before: `$ark.morphs12`.

- Optional keys are listed by name, whether or not they have a default: `{ bar?: number, foo: string = "foo" }`, before: `{ foo: string = "foo", bar?: number }`.

- The `$ark.x` names that functions get in `.json` and `.expression` are names only and no longer resolve through `$ark`.

- Keys are ordered by code unit, where they were ordered as `JSON.stringify` writes them, which moves only keys that first differ at a character JSON escapes or where one ends: `"a"` now precedes `"a b"`.

## Inference

- `.required()` makes a defaulted key required in `inferIn`, as it already did at runtime: `type({ foo: "string = 'bar'" }).required()` infers `{ foo: string }` as input, before: `{ foo?: string }`.
- `.map()` on a union infers each branch: `type({ kind: "'a'", a: "string" }).or({ kind: "'b'", b: "number" }).map(p => p)` is `Type<{ kind: "a"; a: string } | { kind: "b"; b: number }>`, before: `Type<{ kind: "a" | "b" }>`, and the callback's argument holds each branch's props, not only those every branch shares.
- A morph that returns `any` infers `any` as its output: `type({ a: ["string", "=>", s => JSON.parse(s)] }).infer` is `{ a: any }`, before: `{ a: (In: string) => Out<any> }`.
- Without TypeScript's `exactOptionalPropertyTypes`, a key or index signature whose value is a Type allowing `undefined` infers it: `type({ "[string]": Settings.or("undefined") }).infer` is `{ [k: string]: Settings | undefined }`, before: `{ [k: string]: Settings }`, so `settings[k].isHidden` needs a check, as TypeScript's "Object is possibly 'undefined'" says.
- A defaulted key beside an index signature is optional in `inferIn`: `type({ a: "number = 5", "[string]": "number" })` infers `a?: number` as input, before: `a: number`.
- `toJsonSchema()`'s `JsonSchema` no longer declares `exclusiveMinimum` and `exclusiveMaximum`, since `target: "openapi-3.0"` writes `true` for them, so they read as `unknown`.

## @ark/schema

- The set algebra that intersects nodes, reduces unions and writes JSON Schema moved to `arksets`, which `arktype` imports. Using `@ark/schema` alone, `import "arksets"` first, or `.and()` and `toJsonSchema()` throw `Set algebra is not installed` and unions aren't reduced. Its functions, like `intersectNodesRoot` and `reduceBranches`, are exported by `arksets/internal`, as is `discriminantJsonOf(union)`, which replaces a union's `discriminantJson`.
- `BaseNode.compiledMeta` is removed, and `BaseScope.res` (before: `resolutions`) holds an unresolved alias's parse context instead of its id.
- `$.node(kind, input)` takes a node's inner, with children already nodes: `$.node("min", 5)` is now `$.node("min", { rule: 5 })`. Parse the schema format with `rootSchema` or `$.schema`.
- A node's `traverseAllows` and `traverseApply` are `tAllows` and `tApply`. Call them on the node, as in `node.tAllows(data, ctx)`, not detached, as in `[x].every(node.tAllows)`, until the JIT compiles it.
- `NodeParseContext`, what `parseNode` takes, is `{ kind, def, $, id, alias, reduced }`, and the `prereduced` parse option is `reduced`.
- Internal members have short names, each spelled out by its JSDoc, like `is` (before: `hasKind`), `alters` (before: `includesTransform`) and `errN` (before: `currentErrorCount`). [The CHANGELOG's table](https://github.com/arktypeio/arktype/blob/main/ark/type/CHANGELOG.md#shorten-long-internal-names) maps each old name to its new one.
- A morph's input is the first of its `morphs`: its `json` is `{ morphs: ["string", "$ark.trim"] }`, before: `{ in: "string", morphs: ["$ark.trim"] }`, and a schema with `in` still parses to it. Read the input as `head` (before: `inner.in` or `introspectableIn`), what it pipes to as `piped` and the node it ends with as `tail` (before: `lastMorphIfNode`). A node's `rawIn` and `rawOut` are `_in` and `_out`.
- An alias's `resolutionId` (read `resolution.id`), a node's `assertHasKindIn`, `isConstraint` and `isRefinement`, a root's `shortDescription`, a morph's `declareIn` and `serializedMorphs` and a structure's `optionalKeys` are removed.
- A constraint's `compiledCondition`, a predicate's `compiledNegation`, a morph's `compiledMorphs`, a sequence's `optionalsLength` and the `PrecompiledReferences` type are removed. A leaf writes its check with `jsCond(js, data)`.
- Derived keys like the flags `alters` and `ctxPred` (before: `includesTransform`, `includesContextualPredicate`), `kv` and `byKey` (before: `innerEntries`, `propsByKey`) moved from a node's own enumerable keys to its cache, `node.c`, so spreading or iterating a node no longer includes them.

## @ark/util

- `Scanner`'s `jumpToIndex` is removed.
- `isNumericString` and `isWellFormedInteger` read only strings: `isNumericString(5)` throws, before: `true`.
- `$ark.filename` is removed. `$ark.version` still names the `@ark/util` version that created the registry.

## Deep imports

A deep import like `arktype/internal/parser/string.ts` keeps its module's types but loads `arktype/internal` at runtime, which exports the names of every arktype module. Import from `arktype/internal` itself. `@ark/schema`, `@ark/util`, `arkregex` and `arksets` each have an `./internal` entry like it.

## ArkRegex

A capture in one alternation branch is `undefined` in every other branch, so the inferred tuples line up with what `exec` returns:

```ts
const R = regex("^(?:(1)|(2))$")

// before: ["1"] | [undefined, "2"]
type Captures = typeof R.inferCaptures // ["1", undefined] | [undefined, "2"]
```

Other patterns infer what they match more exactly, which can widen or narrow an inferred type:

- `\s` is `string`, before: `" " | "\n" | "\t"`.
- An unbounded run of digits, like `\d+`, is `string`, before: `` `${number}` ``.
- With the `m` flag, `^` and `$` don't anchor: `regex("^abc$", "m")` is `` `${string}abc${string}` ``, before: `"abc"`.
- In a character set, `[\b]` is a backspace and `[\/]` is `/`, before: `""` and an error message.
- A capture inside a lookaround is counted: `regex("^(?=(a))a(b)$")` captures `["a", "b"]`, before: `["b"]`.

## @ark/json-schema

`arktype` is a peer dependency at the version released with `@ark/json-schema`, where it was a dependency, so install the two together. `jsonSchemaToType` reads a schema as a 2020-12 validator does, which changes what some schemas accept:

- `prefixItems` makes its elements optional: `{ type: "array", prefixItems: [{ type: "string" }, { type: "number" }] }` is `[string?, number?, ...unknown[]]` and accepts `[]`, before: `[string, number, ...unknown[]]`.
- `{ type: "object" }` rejects arrays.
- A `uniqueItems` error reads `must be an array of unique items`, before: `(was an array with 2 duplicates: 1, and 3)`.
- The `writeJsonSchema*Message` functions, like `writeJsonSchemaInsufficientKeysMessage`, are no longer exported.

## @ark/fast-check

`arktype` is a peer dependency at the version released with `@ark/fast-check`, where it was a dependency, so install the two together.

## Attest

If you're upgrading attest from before 0.57: under TypeScript 7, attest analyzes with its native API, which needs 7.1 or later, so 7.0.x throws `@ark/attest requires TypeScript 7.1+`. Where attest runs, install TypeScript 7.1 or later, or keep TypeScript 6, which it analyzes with its JS API as before.

Runtime benches run in a loop compiled for each bench, after a warmup, so their times don't compare with earlier versions'. Re-record stored runtime baselines.

- A bench should return the result it computes, so V8 can't drop the work. attest warns when a bench returns `undefined`.
- `until.count` and `until.ms` bound the samples taken after the warmup. Before, they counted sets of 1000 calls and time from the bench's start.
- `benchErrorOnThresholdExceeded: "types"` fails a `.types()` bench that exceeds its baseline, and `"runtime"` no longer does.
- Instantiation counts include evaluating the type a bench returns as fully as displaying it would. Re-record type benches whose results weren't already fully evaluated.

## Package names

Each package publishes under one name. The others, which published the same code, are no longer published, and `@ark/type` and `@ark/regex` are deprecated on npm, so installing one warns with the name to use:

| Install | Instead of |
| - | - |
| `arktype` | `@ark/type`, `@arktype/type` |
| `arkregex` | `@ark/regex`, `@arktype/regex` |
| `@ark/<name>` | `@arktype/<name>`, e.g. `@arktype/schema` |

# Primitives

> Define strings, numbers, bigints, symbols, booleans, null and undefined, with literals, patterns, lengths, ranges and divisors.

## string

### keywords

Reference a keyword anywhere a definition is expected:

```ts
const User = type({
	email: "string.email",
	ids: "string.uuid.v4[]"
})
```

| Alias | Description |
| - | - |
| `string` | a string |
| `string.alpha` | only letters |
| `string.alphanumeric` | only letters and digits 0-9 |
| `string.base58` | base58-encoded |
| `string.base64` | base64-encoded |
| `string.base64.url` | base64url-encoded |
| `string.capitalize` | a morph from a string to capitalized |
| `string.capitalize.preformatted` | capitalized |
| `string.creditCard` | a credit card number |
| `string.date` | a parsable date |
| `string.date.epoch` | an integer string representing a safe Unix timestamp |
| `string.date.epoch.parse` | a morph from an integer string representing a safe Unix timestamp to a Date |
| `string.date.iso` | an ISO 8601 date or date-time |
| `string.date.iso.parse` | a morph from an ISO 8601 date or date-time to a Date |
| `string.date.parse` | a morph from a parsable date to a Date |
| `string.digits` | only digits 0-9 |
| `string.email` | an email address |
| `string.hex` | hex characters only |
| `string.integer` | a well-formed integer string |
| `string.integer.parse` | a morph from a well-formed integer string to an integer |
| `string.ip` | an IP address |
| `string.ip.v4` | an IPv4 address |
| `string.ip.v6` | an IPv6 address |
| `string.json` | a JSON string |
| `string.json.parse` | safe JSON string parser |
| `string.lower` | a morph from a string to lowercase |
| `string.lower.preformatted` | lowercase |
| `string.normalize` | a morph from a string to NFC-normalized unicode |
| `string.normalize.NFC` | a morph from a string to NFC-normalized unicode |
| `string.normalize.NFC.preformatted` | NFC-normalized unicode |
| `string.normalize.NFD` | a morph from a string to NFD-normalized unicode |
| `string.normalize.NFD.preformatted` | NFD-normalized unicode |
| `string.normalize.NFKC` | a morph from a string to NFKC-normalized unicode |
| `string.normalize.NFKC.preformatted` | NFKC-normalized unicode |
| `string.normalize.NFKD` | a morph from a string to NFKD-normalized unicode |
| `string.normalize.NFKD.preformatted` | NFKD-normalized unicode |
| `string.numeric` | a well-formed numeric string |
| `string.numeric.parse` | a morph from a well-formed numeric string and finite to a number |
| `string.regex` | a regex pattern |
| `string.semver` | a semantic version (see <https://semver.org/>) |
| `string.trim` | a morph from a string to trimmed |
| `string.trim.preformatted` | trimmed |
| `string.upper` | a morph from a string to uppercase |
| `string.upper.preformatted` | uppercase |
| `string.url` | a URL string |
| `string.url.parse` | a morph from a URL string to a URL instance |
| `string.uuid` | a UUID |
| `string.uuid.v1` | a UUIDv1 |
| `string.uuid.v2` | a UUIDv2 |
| `string.uuid.v3` | a UUIDv3 |
| `string.uuid.v4` | a UUIDv4 |
| `string.uuid.v5` | a UUIDv5 |
| `string.uuid.v6` | a UUIDv6 |
| `string.uuid.v7` | a UUIDv7 |
| `string.uuid.v8` | a UUIDv8 |

Every keyword, including those for other types, is listed on the [keywords](https://arktype.io/docs/keywords) page.

### literals

Quote a string inside a definition to allow exactly that string. Single and double quotes are equivalent:

```ts
const Literals = type({
	singleQuoted: "'typescript'",
	doubleQuoted: '"arktype"'
})
```

### patterns

A regex literal requires the string to match it. Like a `RegExp`, it is unanchored unless you anchor it with `^` and `$`.

**string**

```ts
const AToZ = type("/^a.*z$/")

// ArkErrors: must be matched by ^a.*z$
AToZ("abc")
```

**fluent**

```ts
const AToZ = type.string.matching(/^a.*z$/)

// ArkErrors: must be matched by ^a.*z$
AToZ("abc")
```

A `RegExp` works as a definition too, e.g. `type({ code: /^a.*z$/ })`.

Regex literals are typed with [ArkRegex](https://arktype.io/docs/regex), so a pattern that constrains the string's shape narrows the inferred type:

```ts
// Type<string>
const Hex = type("/^[0-9a-fA-F]+$/")

// Type<`${number}.${number}.${number}`>
const Semver = type("/^(\\d+)\\.(\\d+)\\.(\\d+)$/")
```

#### e(x)ec mode

Prefix a regex literal with `x` to transform the string into the result of `RegExp.prototype.exec`. The output is the match, not the string, and its capture groups are typed:

```ts
const User = type({
	birthday: "x/^(?<month>\\d{2})-(?<day>\\d{2})-(?<year>\\d{4})$/"
})

const data = User.assert({ birthday: "05-21-1993" })

data.birthday.groups.month // "05"
data.birthday.groups.year // "1993"
```

### lengths

Constrain a string's length with `>`, `>=`, `<`, `<=`, `==` or `!=`:

**string**

```ts
const Bounded = type({
	nonEmpty: "string > 0",
	atMost10: "string <= 10",
	exactly5: "string == 5"
})
```

**fluent**

```ts
const Bounded = type({
	nonEmpty: type.string.moreThanLength(0),
	atMost10: type.string.atMostLength(10),
	exactly5: type.string.exactlyLength(5)
})
```

A range sets both bounds at once, each inclusive or exclusive:

**string**

```ts
// 4 to 6 digits
const Pin = type("4 <= string.digits <= 6")

// ArkErrors: must be at least length 4
Pin("123")
```

**fluent**

```ts
// 4 to 6 digits
const Pin = type.keywords.string.digits.atLeastLength(4).atMostLength(6)

// ArkErrors: must be at least length 4
Pin("123")
```

## number

`number` rejects `NaN`, `Infinity` and `-Infinity`. Allow them in one type with the `number.NaN`, `number.Infinity` and `number.NegativeInfinity` keywords:

```ts
const MaybeInfinite = type("number | number.Infinity | number.NegativeInfinity")
```

To allow them everywhere, configure [`numberAllowsNaN`](https://arktype.io/docs/configuration#numberallowsnan) or [`numberAllowsInfinity`](https://arktype.io/docs/configuration#numberallowsinfinity).

### keywords

```ts
const User = type({
	createdAt: "number.epoch",
	age: "number.integer >= 0"
})
```

| Alias | Description |
| - | - |
| `number` | a number |
| `number.Infinity` | Infinity |
| `number.NaN` | NaN |
| `number.NegativeInfinity` | -Infinity |
| `number.epoch` | an integer representing a safe Unix timestamp |
| `number.integer` | an integer |
| `number.safe` | at least -9007199254740991 and at most 9007199254740991 |

### literals

A number in a definition allows exactly that number:

```ts
const Literals = type({
	number: "1337"
})
```

### ranges

Constrain a number with `>`, `>=`, `<` or `<=`:

**string**

```ts
const Bounded = type({
	positive: "number > 0",
	atMost5: "number <= 5"
})
```

**fluent**

```ts
const Bounded = type({
	positive: type.number.moreThan(0),
	atMost5: type.number.atMost(5)
})
```

A range sets both bounds at once, each inclusive or exclusive:

**string**

```ts
const Percentage = type("0 <= number <= 100")

// ArkErrors: must be at most 100
Percentage(101)
```

**fluent**

```ts
const Percentage = type.number.atLeast(0).atMost(100)

// ArkErrors: must be at most 100
Percentage(101)
```

`!=` excludes one value:

```ts
const NonZero = type("number != 0")

// ArkErrors: must be other than 0
NonZero(0)
```

### divisors

Constrain a number to a multiple of an integer with `%`:

**string**

```ts
const Even = type("number % 2")

// ArkErrors: must be even
Even(3)
```

**fluent**

```ts
const Even = type.number.divisibleBy(2)

// ArkErrors: must be even
Even(3)
```

## bigint

**string**

```ts
const Bigints = type({
	foo: "bigint"
})
```

**fluent**

```ts
const Bigints = type({
	foo: type.bigint
})
```

### literals

Add the suffix `n` to a [number literal](https://arktype.io/docs/primitives#number-literals) to allow exactly that `bigint`:

```ts
const Literals = type({
	bigint: "1337n"
})
```

A [unit expression](https://arktype.io/docs/expressions#unit) like `type.unit(1337n)` does the same.

## symbol

**string**

```ts
const Symbols = type({
	key: "symbol"
})
```

**fluent**

```ts
const Symbols = type({
	key: type.symbol
})
```

To allow one specific symbol, use a [unit expression](https://arktype.io/docs/expressions#unit).

Symbol keys need no special syntax, e.g. `{ [mySymbol]: "string" }`. See [properties](https://arktype.io/docs/objects#properties) to make them optional or defaultable.

## boolean

**string**

```ts
const Booleans = type({
	key: "boolean"
})
```

**fluent**

```ts
const Booleans = type({
	key: type.boolean
})
```

### literals

**string**

```ts
const Booleans = type({
	a: "true",
	b: "false",
	// equivalent to "boolean"
	c: "true | false"
})
```

**fluent**

```ts
const Booleans = type({
	a: type.true,
	b: type.false,
	// equivalent to type.boolean
	c: type.true.or(type.false)
})
```

## null

`"null"` allows exactly `null`, usually in a [union](https://arktype.io/docs/expressions#union):

**string**

```ts
const MyObj = type({
	foo: "number | null"
})
```

**fluent**

```ts
const MyObj = type({
	foo: type.number.or(type.null)
})
```

## undefined

`"undefined"` allows exactly `undefined`, usually in a [union](https://arktype.io/docs/expressions#union):

**string**

```ts
const MyObj = type({
	requiredKey: "number | undefined",
	"optionalKey?": "number | undefined"
})
```

**fluent**

```ts
const MyObj = type({
	requiredKey: type.number.or(type.undefined),
	optionalKey: type.number.or(type.undefined).optional()
})
```

> **Allowing undefined does not make a key optional**
>
> Like in TypeScript, a required key that allows `undefined` must still be present:
>
> ```ts
> const MyObj = type({
> 	key: "number | undefined"
> })
>
> // { key: undefined }
> MyObj({ key: undefined })
>
> // ArkErrors: key must be a number or undefined (was missing)
> MyObj({})
> ```

# Objects

> Define objects, arrays, tuples, dates and class instances, and derive new object types from existing ones.

## properties

An object definition can combine required, optional and defaultable keys with index signatures.

### required

**string**

```ts
const symbolicKey = Symbol()

const MyObj = type({
	requiredKey: "string",
	// nested definitions don't need their own type call
	[symbolicKey]: {
		nested: "unknown"
	}
})
```

**fluent**

```ts
const symbolicKey = Symbol()

const MyObj = type({
	requiredKey: type.string,
	// nested definitions don't need their own type call
	[symbolicKey]: {
		nested: type.unknown
	}
})
```

### optional

**string**

```ts
const symbolicKey = Symbol()

const MyObj = type({
	"optionalKey?": "number[]",
	[symbolicKey]: "string?"
})
```

**fluent**

```ts
const symbolicKey = Symbol()

const MyObj = type({
	optionalKey: type.number.array().optional(),
	[symbolicKey]: type.string.optional()
})
```

**tuple**

```ts
const symbolicKey = Symbol()

const MyObj = type({
	optionalKey: ["number[]", "?"],
	[symbolicKey]: ["string", "?"]
})
```

> **Key or value syntax?**
>
> Prefer the key syntax, `"key?"`. It mirrors TypeScript and reads as what it is: a constraint on whether the key is present, not on its value.
>
> Put `?` on the value when the key is a symbol, when you want go-to-definition and JSDoc on an unquoted key, or when you'd rather not quote keys.

> **An optional key doesn't allow undefined**
>
> ArkType checks optional keys the way TypeScript does with [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes): a missing key is valid, but a key set to `undefined` must allow `undefined`.
>
> ```ts
> const MyObj = type({
> 	"key?": "number"
> })
>
> // {}
> MyObj({})
>
> // ArkErrors: key must be a number
> MyObj({ key: undefined })
> ```
>
> To allow it, add `undefined` to the value: `"key?": "number | undefined"`. You can also set [`exactOptionalPropertyTypes`](https://arktype.io/docs/configuration#exactoptionalpropertytypes) to `false` globally.

### defaultable

A defaultable key is optional in the input. When it is missing, the output has its default.

**string**

```ts
const MyObj = type({
	defaultableKey: "boolean = false"
})

// { defaultableKey: false }
MyObj({})
```

**fluent**

```ts
const MyObj = type({
	defaultableKey: type.boolean.default(false)
})

// { defaultableKey: false }
MyObj({})
```

**tuple**

```ts
const MyObj = type({
	defaultableKey: ["boolean", "=", false]
})

// { defaultableKey: false }
MyObj({})
```

`= []` and `= {}` give each output its own new array or object, so mutating one never changes another:

```ts
const MyObj = type({
	values: "string[] = []",
	meta: "object = {}"
})
```

For any other object, default to a function that returns it, e.g. `type.Date.default(() => new Date())`.

> **Optional and default only work in objects and tuples**
>
> `number.optional()` and `number.default(0)` don't return a `Type`. They return the tuple definitions `[Type<number>, "?"]` and `[Type<number>, "=", 0]`, which are only valid as a property or a tuple element. `type("string?")` throws a `ParseError`.
>
> For a `Type` that accepts `undefined`, use a union like `type("string | undefined")`. To replace `undefined` with a value, add a morph:
>
> ```ts
> const FallbackString = type("string | undefined").pipe(v => v ?? "")
> ```

### index

An index signature constrains every key that matches it:

```ts
const Scores = type({
	"[string]": "number"
})
```

The key can be any string or symbol type, like `symbol`, `string | symbol`, a keyword like `string.uuid` or a regex literal:

```ts
const DataAttributes = type({
	"[/^data-/]": "string"
})

// ArkErrors: ["data-id"] must be a string
DataAttributes({ "data-id": 1 })
```

A union of literal keys becomes those named keys, so `"['a' | 'b']": "number"` is `{ a: number, b: number }`.

`Record` is available as a [generic keyword](https://arktype.io/docs/generics#keywords), e.g. `type("Record<string, number>")` or `type.Record("string", "number")`.

### undeclared

By default, ArkType allows keys you didn't declare, like TypeScript does. That lets you validate an object you already have without copying it, and skipping the check for extra keys is faster.

To reject or delete undeclared keys, set `"+"` in the object, or [configure](https://arktype.io/docs/configuration#onundeclaredkey) a different default for every object:

**string**

```ts
// fail if any string key other than "onlyAllowedKey" is present
const MyClosedObject = type({
	"+": "reject",
	onlyAllowedKey: "string"
})

// delete every key other than "onlyPreservedKey"
const MyStrippedObject = type({
	"+": "delete",
	onlyPreservedKey: "string"
})

// allow and keep undeclared keys (the default)
const MyOpenObject = type({
	"+": "ignore",
	nonexclusiveKey: "number"
})
```

**fluent**

```ts
// fail if any string key other than "onlyAllowedKey" is present
const MyClosedObject = type({
	onlyAllowedKey: "string"
}).onUndeclaredKey("reject")

// delete every key other than "onlyPreservedKey"
const MyStrippedObject = type({
	onlyPreservedKey: "string"
}).onUndeclaredKey("delete")

// allow and keep undeclared keys (the default)
const MyOpenObject = type({
	nonexclusiveKey: "number"
}).onUndeclaredKey("ignore")
```

`"ignore"` only matters if you configured a different default.

A rejected key is an error with the code `undeclared`:

```ts
const MyClosedObject = type({
	"+": "reject",
	onlyAllowedKey: "string"
})

// ArkErrors: extraKey must be removed
MyClosedObject({ onlyAllowedKey: "ok", extraKey: 1 })
```

Both act on string keys: `"reject"` checks only an object's string keys, and `"delete"` builds a new object holding only its declared keys. So an undeclared symbol key passes `"reject"` and is dropped by `"delete"`, and reject types that differ only by a symbol key overlap, so a union of them with a morph is indeterminate.

`"delete"`'s output lists the declared keys in the order the definition declares them, as Zod does, then any keys matching an index signature in the input's order.

`.onDeepUndeclaredKey()` applies the same behavior to every nested object:

```ts
const MyDeeplyStrippedObject = type({
	preserved: "string",
	nested: {
		preserved: "string"
	}
}).onDeepUndeclaredKey("delete")

// { nested: { preserved: "b" }, preserved: "a" }
MyDeeplyStrippedObject({
	preserved: "a",
	extra: 1,
	nested: { preserved: "b", extra: 2 }
})
```

> **Prefer in-object syntax where possible**
>
> `.onUndeclaredKey()` and `.configure()` rebuild the whole type they're called on, so creating a type with them is slower than writing `"+"` in the object. Validation is equally fast either way. Methods like `.or()` and `.pipe()` reference the original type rather than rebuilding it, so they have no such cost.

### merge

Merging adds properties to an object or replaces existing ones, like JavaScript's [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). Write it as a `"..."` key in the object, `.merge()` or the `Merge` generic:

**string**

```ts
const User = type({ isAdmin: "false", name: "string" })

// Type<{ name: string; isAdmin: true; permissions: string[] }>
const Admin = type({
	"...": User,
	isAdmin: "true",
	permissions: "string[]"
})
```

**fluent**

```ts
const User = type({ isAdmin: "false", name: "string" })

// Type<{ name: string; isAdmin: true; permissions: string[] }>
const Admin = User.merge({
	isAdmin: "true",
	permissions: "string[]"
})
```

**generic**

```ts
const types = type.module({
	User: { isAdmin: "false", name: "string" },
	AdminProps: { isAdmin: "true", permissions: "string[]" },
	// { name: string; isAdmin: true; permissions: string[] }
	Admin: "Merge<User, AdminProps>"
})
```

A key in both objects takes its value from the merged object. An [intersection](https://arktype.io/docs/expressions#intersection) would instead intersect the two values, and `false & true` would throw a `ParseError`. When the keys don't overlap, the two give the same type, but merging is less work to compute, both when the type is created and in your editor, so prefer it for combining properties.

Like the other [structural transformations](https://arktype.io/docs/objects#properties-structural), `merge` builds a new object from the properties, so a root narrow or metadata is not carried over.

#### n-ary

`type.merge` merges any number of objects, each overriding the ones before it:

```ts
// Type<{ b: number; a?: 1 }>
const Merged = type.merge({ a: "string" }, { b: "number" }, { "a?": "1" })
```

### escapes

Escape a key's `?`, the `[` of a key in brackets, or a key that is exactly `+`, `...` or `@`, with a backslash to use it literally:

```ts
// Type<{ "isAdmin?": boolean; "+": string; "[id]"?: string }>
const Escaped = type({
	"isAdmin\\?": "boolean",
	"\\+": "string",
	"\\[id]?": "string"
})

// ArkErrors: ["isAdmin?"] must be boolean (was missing)
Escaped({ "+": "x" })
```

An index signature can't be optional, so a key like `"[id]?"` throws a `ParseError` unless its `[` is escaped.

### keyof

Like in TypeScript, `keyof` extracts an object's keys as a union:

**string**

```ts
const types = type.module({
	UsedCar: {
		originallyPurchased: "string.date",
		remainingWheels: "number"
	},
	// "originallyPurchased" | "remainingWheels"
	UsedCarKey: "keyof UsedCar"
})
```

**fluent**

```ts
const UsedCar = type({
	originallyPurchased: "string.date",
	remainingWheels: "number"
})

// Type<"originallyPurchased" | "remainingWheels">
const UsedCarKey = UsedCar.keyof()
```

**tuple**

```ts
const UsedCar = type({
	originallyPurchased: "string.date",
	remainingWheels: "number"
})

// Type<"originallyPurchased" | "remainingWheels">
const UsedCarKey = type(["keyof", UsedCar])
```

**args**

```ts
const UsedCar = type({
	originallyPurchased: "string.date",
	remainingWheels: "number"
})

// Type<"originallyPurchased" | "remainingWheels">
const UsedCarKey = type("keyof", UsedCar)
```

Also like in TypeScript, a `[string]` index signature absorbs the named keys, so `keyof` is `string`:

```ts
const RecordWithSpecialKeys = type({
	"[string]": "unknown",
	verySpecialKey: "number"
})

// true
RecordWithSpecialKeys.keyof().equals("string")
```

> **ArkType's keyof never includes number**
>
> TypeScript's `keyof` can include `number`, but JavaScript has no numeric keys: `{ 4: true }` and `{ "4": true }` are the same object, and `Object.keys` returns `["4"]` for both. ArkType's `keyof` only returns `string` and `symbol` keys, the two kinds of key an object can have.
>
> **Why ArkType diverges from TypeScript here**
>
> In a set-based type system, two types that describe the same values need the same representation. TypeScript keeps separate numeric and string representations of the same key, which leads to results like this:
>
> ```ts
> type Thing1 = {
> 	[x: string]: unknown
> }
>
> // Thing2 describes the same values as Thing1
> type Thing2 = Record<string, unknown>
>
> type Key1 = keyof Thing1
> // type Key1 = string | number
>
> type Key2 = keyof Thing2
> // type Key2 = string
> ```

### get

Like an indexed access type in TypeScript (`User["name"]`), `get` extracts the type of the value at a key:

```ts
const Manatee = type({
	isFriendly: "true",
	snorf: {
		uses: "string[]"
	}
})

// Type<true>
const IsFriendly = Manatee.get("isFriendly")

// pass more keys to access nested properties
// Type<string[]>
const SnorfUses = Manatee.get("snorf", "uses")
```

The key can also be a union, a literal or an index signature, and the object can be a union with optional keys. The [`get` tests](https://github.com/arktypeio/arktype/blob/main/ark/type/__tests__/get.test.ts) cover each case.

> **Extracting part of a type can be an antipattern**
>
> Before using `get`, `pick` or `omit` on a type you defined, consider defining that part as its own type and referencing it. Composing small types is usually clearer and faster than extracting parts of a large one.

### structural transformations

`merge`, `pick`, `omit`, `required`, `partial` and `map` each return a **new object built from the properties** of the `Type` they're called on, rather than referencing that `Type`.

> **Only properties are carried over**
>
> Anything attached to the object itself is dropped: most importantly a root [narrow](https://arktype.io/docs/expressions#narrow) or [filter](https://arktype.io/docs/expressions#filter), but also [metadata](https://arktype.io/docs/configuration#metadata) like `.describe(...)`. Constraints on the properties are kept.
>
> ```ts
> const User = type({
> 	name: "string",
> 	email: "string"
> }).narrow(user => user.email.includes("@"))
>
> // the narrow is not a property, so PartialUser doesn't have it
> const PartialUser = User.partial()
>
> // { email: "not an email" }
> PartialUser({ email: "not an email" })
> ```
>
> Reapply what you still need to the result:
>
> ```ts
> const PartialUser = type({
> 	name: "string",
> 	email: "string"
> })
> 	.partial()
> 	.narrow(user => user.email?.includes("@") ?? true)
> ```
>
> A root [morph](https://arktype.io/docs/expressions#pipe) can't be reduced to properties, so transforming a type like `type({ name: "string" }).pipe(user => user)` throws a `ParseError` instead of dropping it.

### pick / omit

Keep or remove specific properties:

```ts
const User = type({
	name: "string",
	email: "string.email",
	"age?": "number"
})

// Type<{ name: string; email: string }>
const NameAndEmail = User.pick("name", "email")

// Type<{ name: string; age?: number }>
const WithoutEmail = User.omit("email")
```

In a definition, use the `Pick` and `Omit` [generics](https://arktype.io/docs/generics#keywords). Their keys are definitions, so quote each one:

```ts
const types = type.module({
	User: {
		name: "string",
		email: "string.email",
		"age?": "number"
	},
	NameAndEmail: "Pick<User, 'name' | 'email'>",
	WithoutEmail: "Omit<User, 'email'>"
})
```

### required / partial

Make every named property required or optional:

```ts
const User = type({
	name: "string",
	"email?": "string.email",
	"age?": "number"
})

// Type<{ name: string; email: string; age: number }>
const RequiredUser = User.required()

// Type<{ name?: string; email?: string; age?: number }>
const PartialUser = User.partial()
```

`required` also removes defaults, so a defaulted key becomes a plain required key:

```ts
// Type<{ foo: string }>
const T = type({ foo: "string = 'bar'" }).required()

// ArkErrors: foo must be a string (was missing)
T({})
```

In a definition, use the `Required` and `Partial` [generics](https://arktype.io/docs/generics#keywords), e.g. `"Partial<User>"` in a scope.

> **Arrays and tuples mirror TypeScript's Required and Partial**
>
> Like the mapped types they're named for, `required` and `partial` apply to an array's or tuple's elements:
>
> ```ts
> // Type<[string?, number?]>
> const PartialPair = type(["string", "number"]).partial()
>
> // Type<[string, number]>
> const RequiredPair = type(["string", "number?"]).required()
> ```
>
> They only change whether an element must be present, never the values it allows. TypeScript also adds `undefined` to variadic elements and index signature values, since it has no way to mark them optional. ArkType doesn't, so `type("string[]").partial()` is still `string[]`.
>
> A postfix element can't follow an optional one, in ArkType or in TypeScript, so `partial` throws a `ParseError` on a tuple like `[string, ...number[], boolean]`.

### readonly

Mark every property as `readonly`. This only affects the inferred type; the output isn't frozen.

```ts
// Type<{ readonly id: number; readonly name: string }>
const Frozen = type({
	id: "number",
	name: "string"
}).readonly()
```

### map

`map` transforms each property of an object. The function receives a prop with its `key`, `value` (a `Type`) and `kind` (`"required"` or `"optional"`), and returns a `{ key, value }` object, optionally with `kind`:

```ts
const Name = type({
	first: "string",
	last: "string"
})

// Type<{ first: string | null; last: string | null }>
const NullableName = Name.map(prop => ({
	key: prop.key,
	value: prop.value.or("null")
}))
```

Return `[]` to remove a property, or several props to add more than one:

```ts
const User = type({
	name: "string",
	"age?": "number"
})

// Type<{ name: string }>
const NameOnly = User.map(prop => (prop.key === "age" ? [] : prop))
```

### props

`props` lists an object's properties, with required keys first, then optional keys, each sorted by name:

```ts
const User = type({
	name: "string",
	"age?": "number",
	role: "'admin' | 'user' = 'user'"
})

for (const prop of User.props) {
	console.log(prop.kind) // "required", "optional", "optional"
	console.log(prop.key) // "name", "age", "role"
	console.log(prop.value.expression) // "string", "number", '"admin" | "user"'
	if ("default" in prop) console.log(prop.default) // "user"
}
```

## arrays

**string**

```ts
const Arrays = type({
	key: "string[]"
})
```

**fluent**

```ts
const Arrays = type({
	key: type.string.array()
})
```

**tuple**

```ts
const Arrays = type({
	key: ["string", "[]"]
})
```

**args**

```ts
const Arrays = type({
	key: type("string", "[]")
})
```

### lengths

Constrain an array's length with `>`, `>=`, `<`, `<=`, `==` or `!=`:

**string**

```ts
const Bounded = type({
	nonEmpty: "string[] > 0",
	atMost5: "boolean[] <= 5",
	pair: "number[] == 2"
})
```

**fluent**

```ts
const Bounded = type({
	nonEmpty: type.string.array().moreThanLength(0),
	atMost5: type.boolean.array().atMostLength(5),
	pair: type.number.array().exactlyLength(2)
})
```

A range sets both bounds at once, each inclusive or exclusive:

**string**

```ts
const Tags = type("0 < string[] <= 10")

// ArkErrors: must be non-empty
Tags([])
```

**fluent**

```ts
const Tags = type.string.array().moreThanLength(0).atMostLength(10)

// ArkErrors: must be non-empty
Tags([])
```

## tuples

Like objects, tuples are structures whose values are nested definitions. Like TypeScript, ArkType supports prefix, defaultable, optional, variadic and postfix elements, with the same rules for combining them.

### prefix

**string**

```ts
const MyTuple = type([
	"string",
	// object definitions can be nested in tuples, and vice versa
	{
		coordinates: ["number", "number"]
	}
])
```

**fluent**

```ts
const MyTuple = type([
	type.string,
	// object definitions can be nested in tuples, and vice versa
	{
		coordinates: [type.number, type.number]
	}
])
```

### defaultable

A defaultable element is optional in the input. When it is missing, the output has its default.

Defaultable elements follow the prefix elements and come before any optional elements. Like optional elements, they can't be combined with postfix elements.

**string**

```ts
const MyTuple = type(["string", "boolean = false", "number = 0"])

// ["a", false, 0]
MyTuple(["a"])
```

**fluent**

```ts
const MyTuple = type([
	type.string,
	type.boolean.default(false),
	type.number.default(0)
])

// ["a", false, 0]
MyTuple(["a"])
```

**tuple**

```ts
const MyTuple = type(["string", ["boolean", "=", false], ["number", "=", 0]])

// ["a", false, 0]
MyTuple(["a"])
```

### optional

An optional element may be absent from the input and has no default.

Optional elements follow the prefix and defaultable elements, and come before a variadic element or the end of the tuple. Like in TypeScript, they can't be combined with postfix elements.

**string**

```ts
const MyTuple = type(["string", "boolean?", "number?"])

// ["a"]
MyTuple(["a"])
```

**fluent**

```ts
const MyTuple = type([
	type.string,
	type.boolean.optional(),
	type.number.optional()
])

// ["a"]
MyTuple(["a"])
```

**tuple**

```ts
const MyTuple = type(["string", ["boolean", "?"], ["number", "?"]])

// ["a"]
MyTuple(["a"])
```

### variadic

Like in TypeScript, a variadic element allows zero or more consecutive values of a type. A tuple can have at most one. Write it as `"..."` followed by an array:

**string**

```ts
// a string followed by zero or more numbers
const MyTuple = type(["string", "...", "number[]"])
```

**fluent**

```ts
// a string followed by zero or more numbers
const MyTuple = type([type.string, "...", type.number.array()])
```

### postfix

Postfix elements are required elements after a variadic element. They can't be combined with optional or defaultable elements.

**string**

```ts
// zero or more numbers followed by a boolean, then a string
const MyTuple = type(["...", "number[]", "boolean", "string"])
```

**fluent**

```ts
// zero or more numbers followed by a boolean, then a string
const MyTuple = type(["...", type.number.array(), type.boolean, type.string])
```

## dates

`Date` allows a valid `Date` instance. An invalid date, like `new Date("x")`, is rejected:

```ts
// ArkErrors: must be a Date
type.Date(new Date("x"))
```

To accept invalid dates everywhere, configure [`dateAllowsInvalid`](https://arktype.io/docs/configuration#dateallowsinvalid).

### literals

A date literal, `d'...'` or `d"..."`, is a `Date` with an exact value. They're mostly useful as [range](https://arktype.io/docs/objects#dates-ranges) bounds.

```ts
const Literals = type({
	singleQuoted: "d'1970-01-01'",
	doubleQuoted: 'd"1970-01-01"'
})
```

A literal, like a string passed as a date limit, must be the same instant on every machine, so it can be an ISO date like `2025-01-01` (which is UTC), an ISO date-time with `Z` or an offset like `2025-01-01T12:00+01:00`, or a number of epoch milliseconds. Any other literal, like `d'notadate'` or `d'2025-01-01T12:00'`, is a `ParseError`.

### ranges

Constrain a `Date` with `>`, `>=`, `<`, `<=`, `==` or `!=`. A bound is either a [date literal](https://arktype.io/docs/objects#dates-literals) or a number of milliseconds since the Unix epoch.

**string**

```ts
const Bounded = type({
	inThePast: `Date < ${Date.now()}`,
	from2000: "Date >= d'2000-01-01'",
	before2100: "Date < d'2100-01-01'"
})
```

**fluent**

```ts
const Bounded = type({
	inThePast: type.Date.earlierThan(Date.now()),
	from2000: type.Date.atOrAfter("2000-01-01"),
	before2100: type.Date.earlierThan("2100-01-01")
})
```

The fluent methods are `laterThan`, `atOrAfter`, `earlierThan` and `atOrBefore`.

A range sets both bounds at once, each inclusive or exclusive:

**string**

```ts
const tenYearsAgo = new Date().setFullYear(new Date().getFullYear() - 10)

const Recent = type(`${tenYearsAgo} <= Date < ${Date.now()}`)
```

**fluent**

```ts
const tenYearsAgo = new Date().setFullYear(new Date().getFullYear() - 10)

const Recent = type.Date.atOrAfter(tenYearsAgo).earlierThan(Date.now())
```

Descriptions and error messages write dates in UTC. A date at UTC midnight is written as its calendar date:

```ts
// "a Date and January 1, 2023 or later"
type("Date >= d'2023-01-01'").description

// "a Date and January 1, 2023, 2:30 PM UTC or later"
type("Date >= d'2023-01-01T14:30Z'").description
```

## instanceof

Most built-in classes like `Array`, `Date` and `Map` are [keywords](https://arktype.io/docs/keywords#instanceof). Use `instanceof` for your own classes:

**fluent**

```ts
class MyClass {}

const Instance = type.instanceOf(MyClass)
```

**tuple**

```ts
class MyClass {}

const Instance = type(["instanceof", MyClass])
```

**args**

```ts
class MyClass {}

const Instance = type("instanceof", MyClass)
```

> **Array is the only constructor that works across realms**
>
> Constructors are compared by identity, so a value created in another realm, like an `<iframe>` or a `node:vm` context, is not an instance of the constructor in yours. `Array` is checked with `Array.isArray`, so it also matches arrays from another realm.

### keywords

The [keywords](https://arktype.io/docs/keywords#instanceof) page lists every built-in class keyword, along with the subtypes of [Array](https://arktype.io/docs/keywords#array) and [FormData](https://arktype.io/docs/keywords#formdata).

Keywords for web platform classes, like `Blob`, `File`, `URL`, `FormData`, `Headers`, `Request` and `Response`, throw when used in a runtime that doesn't define that class, e.g. `'Blob' is unresolvable`.

# Keywords

> Every built-in keyword, from TypeScript's own types to subtypes like string.email and generics like Pick.

## TypeScript

TypeScript's built-in types are keywords, except `any` and `void`, which don't mean anything useful at runtime. If you need `any`, use `unknown.any`.

**string**

```ts
const Keywords = type({
	string: "string",
	date: "Date"
})
```

**fluent**

```ts
const Keywords = type({
	string: type.string,
	date: type.Date
})
```

These keywords are attached directly to `type`: `string`, `number`, `bigint`, `boolean`, `symbol`, `undefined`, `null`, `object`, `unknown`, `true`, `false`, `never`, `Key`, `Array`, `Date`, `Record` and `arrayIndex`. Every keyword is available in `type.keywords`.

## Subtypes

A subtype keyword refines or transforms its parent, like `string.email` or `string.date.parse`. To find them in your editor, start a definition like `"string."` and let autocomplete list them.

**string**

```ts
const Keywords = type({
	dateString: "string.date",
	isoDateString: "string.date.iso",
	parsedDate: "string.date.parse",
	parsedIsoDate: "string.date.iso.parse"
})
```

**fluent**

```ts
const Keywords = type({
	dateString: type.keywords.string.date.root,
	isoDateString: type.keywords.string.date.iso.root,
	parsedDate: type.keywords.string.date.parse,
	parsedIsoDate: type.keywords.string.date.iso.parse
})
```

A keyword with subtypes, like `string.date`, is a module. Its `.root` is the keyword's own `Type`.

## All keywords

These are all the keywords `type` resolves. To define your own, see [scopes](https://arktype.io/docs/scopes).

### string

| Alias | Description |
| - | - |
| `string` | a string |
| `string.alpha` | only letters |
| `string.alphanumeric` | only letters and digits 0-9 |
| `string.base58` | base58-encoded |
| `string.base64` | base64-encoded |
| `string.base64.url` | base64url-encoded |
| `string.capitalize` | a morph from a string to capitalized |
| `string.capitalize.preformatted` | capitalized |
| `string.creditCard` | a credit card number |
| `string.date` | a parsable date |
| `string.date.epoch` | an integer string representing a safe Unix timestamp |
| `string.date.epoch.parse` | a morph from an integer string representing a safe Unix timestamp to a Date |
| `string.date.iso` | an ISO 8601 date or date-time |
| `string.date.iso.parse` | a morph from an ISO 8601 date or date-time to a Date |
| `string.date.parse` | a morph from a parsable date to a Date |
| `string.digits` | only digits 0-9 |
| `string.email` | an email address |
| `string.hex` | hex characters only |
| `string.integer` | a well-formed integer string |
| `string.integer.parse` | a morph from a well-formed integer string to an integer |
| `string.ip` | an IP address |
| `string.ip.v4` | an IPv4 address |
| `string.ip.v6` | an IPv6 address |
| `string.json` | a JSON string |
| `string.json.parse` | safe JSON string parser |
| `string.lower` | a morph from a string to lowercase |
| `string.lower.preformatted` | lowercase |
| `string.normalize` | a morph from a string to NFC-normalized unicode |
| `string.normalize.NFC` | a morph from a string to NFC-normalized unicode |
| `string.normalize.NFC.preformatted` | NFC-normalized unicode |
| `string.normalize.NFD` | a morph from a string to NFD-normalized unicode |
| `string.normalize.NFD.preformatted` | NFD-normalized unicode |
| `string.normalize.NFKC` | a morph from a string to NFKC-normalized unicode |
| `string.normalize.NFKC.preformatted` | NFKC-normalized unicode |
| `string.normalize.NFKD` | a morph from a string to NFKD-normalized unicode |
| `string.normalize.NFKD.preformatted` | NFKD-normalized unicode |
| `string.numeric` | a well-formed numeric string |
| `string.numeric.parse` | a morph from a well-formed numeric string and finite to a number |
| `string.regex` | a regex pattern |
| `string.semver` | a semantic version (see <https://semver.org/>) |
| `string.trim` | a morph from a string to trimmed |
| `string.trim.preformatted` | trimmed |
| `string.upper` | a morph from a string to uppercase |
| `string.upper.preformatted` | uppercase |
| `string.url` | a URL string |
| `string.url.parse` | a morph from a URL string to a URL instance |
| `string.uuid` | a UUID |
| `string.uuid.v1` | a UUIDv1 |
| `string.uuid.v2` | a UUIDv2 |
| `string.uuid.v3` | a UUIDv3 |
| `string.uuid.v4` | a UUIDv4 |
| `string.uuid.v5` | a UUIDv5 |
| `string.uuid.v6` | a UUIDv6 |
| `string.uuid.v7` | a UUIDv7 |
| `string.uuid.v8` | a UUIDv8 |

### number

| Alias | Description |
| - | - |
| `number` | a number |
| `number.Infinity` | Infinity |
| `number.NaN` | NaN |
| `number.NegativeInfinity` | -Infinity |
| `number.epoch` | an integer representing a safe Unix timestamp |
| `number.integer` | an integer |
| `number.safe` | at least -9007199254740991 and at most 9007199254740991 |

### other

| Alias | Description |
| - | - |
| `Key` | a string or a symbol |
| `bigint` | a bigint |
| `boolean` | boolean |
| `false` | false |
| `never` | never |
| `null` | null |
| `symbol` | a symbol |
| `true` | true |
| `undefined` | undefined |
| `unknown` | unknown |
| `unknown.any` | unknown |

### object

| Alias | Description |
| - | - |
| `object` | an object |
| `object.json` | { \[string]: $jsonData } |
| `object.json.stringify` | a morph from { \[string]: $jsonData } to a string |

### array

| Alias | Description |
| - | - |
| `Array` | an array |
| `Array.index` | matched by ^(?:0\|\[1-9]\d\*)$ |
| `Array.liftFrom` | a generic type for liftFromHkt |
| `Array.readonly` | an array |
| `ArrayBuffer` | an ArrayBuffer instance |

### FormData

| Alias | Description |
| - | - |
| `FormData` | a FormData instance |
| `FormData.parse` | a morph from a FormData instance to an object representing parsed form data |
| `FormData.parsed` | an object representing parsed form data |
| `FormData.value` | a string or a File instance |

### TypedArray

| Alias | Description |
| - | - |
| `BigInt64Array` | a BigInt64Array |
| `BigUint64Array` | a BigUint64Array |
| `Float32Array` | a Float32Array |
| `Float64Array` | a Float64Array |
| `Int16Array` | an Int16Array |
| `Int32Array` | an Int32Array |
| `Int8Array` | an Int8Array |
| `TypedArray.BigInt64` | a BigInt64Array |
| `TypedArray.BigUint64` | a BigUint64Array |
| `TypedArray.Float32` | a Float32Array |
| `TypedArray.Float64` | a Float64Array |
| `TypedArray.Int16` | an Int16Array |
| `TypedArray.Int32` | an Int32Array |
| `TypedArray.Int8` | an Int8Array |
| `TypedArray.Uint16` | a Uint16Array |
| `TypedArray.Uint32` | a Uint32Array |
| `TypedArray.Uint8` | a Uint8Array |
| `TypedArray.Uint8Clamped` | a Uint8ClampedArray |
| `Uint16Array` | a Uint16Array |
| `Uint32Array` | a Uint32Array |
| `Uint8Array` | a Uint8Array |
| `Uint8ClampedArray` | a Uint8ClampedArray |

### instanceof

| Alias | Description |
| - | - |
| `Blob` | a Blob instance |
| `Date` | a Date |
| `Error` | an Error |
| `File` | a File instance |
| `Function` | a function |
| `Headers` | a Headers instance |
| `Map` | a Map |
| `Promise` | a Promise |
| `RegExp` | a RegExp |
| `Request` | a Request instance |
| `Response` | a Response instance |
| `Set` | a Set |
| `URL` | a URL instance |
| `WeakMap` | a WeakMap |
| `WeakSet` | a WeakSet |

### generic

| Alias | Description |
| - | - |
| `Exclude` | exclude branches of a union like \`Exclude("boolean", "true")\` |
| `Extract` | extract branches of a union like \`Extract("0 \| false \| 1", "number")\` |
| `Merge` | merge an object's properties onto another like \`Merge(User, { isAdmin: "true" })\` |
| `Omit` | omit a set of properties from an object like \`Omit(User, "age")\` |
| `Partial` | make all named properties of an object optional like \`Partial(User)\` |
| `Pick` | pick a set of properties from an object like \`Pick(User, "name \| age")\` |
| `Record` | instantiate an object from an index signature and corresponding value type like \`Record("string", "number")\` |
| `Required` | make all named properties of an object required like \`Required(User)\` |

# Expressions

> Combine, refine, transform and annotate types with operators like unions, intersections, narrows, pipes, brands and metadata.

An expression combines or modifies other definitions. Most expressions can be written four ways:

- **string**: embedded in a string definition, like `"string | number"`
- **fluent**: a method on a `Type`, like `type.string.or(type.number)`
- **tuple**: an array definition, like `["string", "|", "number"]`
- **args**: the same elements passed to `type` as arguments, like `type("string", "|", "number")`

They're interchangeable, so use whichever reads best. Where an operand is a function or a value like a symbol, use the fluent, tuple or args form.

| Expression | String | Fluent | Tuple / args |
| - | - | - | - |
| [intersection](https://arktype.io/docs/expressions#intersection) | `"a & b"` | `.and(b)` | `[a, "&", b]` |
| [union](https://arktype.io/docs/expressions#union) | `"a \| b"` | `.or(b)` | `[a, "\|", b]` |
| [array](https://arktype.io/docs/objects#arrays) | `"a[]"` | `.array()` | `[a, "[]"]` |
| [keyof](https://arktype.io/docs/objects#properties-keyof) | `"keyof a"` | `.keyof()` | `["keyof", a]` |
| [brand](https://arktype.io/docs/expressions#brand) | `"a#name"` | `.brand("name")` | |
| [narrow](https://arktype.io/docs/expressions#narrow) | | `.narrow(fn)` | `[a, ":", fn]` |
| [filter](https://arktype.io/docs/expressions#filter) | | `.filter(fn)` | |
| [pipe](https://arktype.io/docs/expressions#pipe) | | `.pipe(fn)` | `[a, "=>", fn]` |
| [to](https://arktype.io/docs/expressions#to) | `"a \|> b"` | `.to(b)` | `[a, "\|>", b]` |
| [unit](https://arktype.io/docs/expressions#unit) | a literal, `"'a'"` | `type.unit(value)` | `["===", value]` |
| [meta](https://arktype.io/docs/expressions#meta) | | `.configure(meta)` | `[a, "@", meta]` |
| [instanceof](https://arktype.io/docs/objects#instanceof) | | `type.instanceOf(Class)` | `["instanceof", Class]` |

Optional (`?`), defaultable (`=`) and spread (`...`) definitions only apply to properties and tuple elements. They're covered on the [objects](https://arktype.io/docs/objects) page.

## Intersection

Like its TypeScript counterpart, an intersection creates a `Type` that enforces the constraints of both operands.

**string**

```ts
// an email address at arktype.io
const ArkEmail = type("string.email & /@arktype\\.io$/")

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

**fluent**

```ts
// an email address at arktype.io
const ArkEmail = type("string.email").and(/@arktype\.io$/)

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

**tuple**

```ts
// an email address at arktype.io
const ArkEmail = type(["string.email", "&", /@arktype\.io$/])

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

**args**

```ts
// an email address at arktype.io
const ArkEmail = type("string.email", "&", /@arktype\.io$/)

// ArkErrors: must be matched by @arktype\.io$
ArkEmail("a@b.com")
```

> **To combine properties, merge instead**
>
> Intersecting objects is more work to compute than [merging](https://arktype.io/docs/objects#merge) them, both when the type is created and in your editor. Unless you need overlapping keys' values intersected, merge.

### n-ary

`type.and` intersects any number of definitions:

```ts
// Type<{ foo: string; bar: number; baz: string }>
const FooBarBaz = type.and(
	{ foo: "string" },
	{ bar: "number" },
	{ baz: "string" }
)
```

## Union

A union allows a value that satisfies either operand. ArkType discriminates unions automatically: where a value like its type or a literal key tells the branches apart, it checks that first instead of trying each branch, which keeps validation fast and errors specific. Where the discriminant can't place data, like a number where every branch is an object, each branch reports its own error, as in an undiscriminated union.

**string**

```ts
const StringOrNumber = type("string | number")

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

**fluent**

```ts
const StringOrNumber = type.string.or(type.number)

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

**tuple**

```ts
const StringOrNumber = type(["string", "|", "number"])

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

**args**

```ts
const StringOrNumber = type("string", "|", "number")

// ArkErrors: must be a number or a string
StringOrNumber(true)
```

When no branch matches the discriminant, like a value of the wrong type here, the error's code is `discriminant`. See [errors](https://arktype.io/docs/errors) for the fields it carries.

### n-ary

`type.or` unions any number of definitions:

```ts
// Type<string | number | { key: unknown }>
const Union = type.or(type.string, "number", { key: "unknown" })
```

> **A union that could transform the same input in different ways throws a ParseError**
>
> ```ts
> // operands overlap, but neither transforms data
> const Okay = type("number > 0").or("number < 10")
>
> // an operand transforms data, but the inputs don't overlap
> const AlsoOkay = type("string.numeric.parse").or({ box: "string" })
>
> // ParseError: An unordered union of a type including a morph and a type with overlapping input is indeterminate
> const Bad = type({ box: "string.numeric.parse" }).or({ box: "string" })
> ```
>
> To fix it, make the inputs disjoint, e.g. by narrowing a morph's input, or pipe the union of their inputs to a single morph:
>
> ```ts
> // only numeric strings are parsed, so no input reaches two branches
> const Narrowed = type("string.numeric.parse | number | null")
>
> // one morph decides how to transform each input
> const Piped = type("unknown").pipe(v => (v === null ? v : Number(v)))
> ```
>
> **Why this isn't allowed**
>
> `Bad` says two things about the same input:
>
> - if `box` is a string, parse it as a number
> - if `box` is a string, keep it as a string
>
> The order of a union's branches doesn't affect its result, so there's no way to choose between them. The same applies when the transformed keys differ: `type({ a: "string.numeric.parse" }).or({ b: "string.numeric.parse" })` throws too, since an input like `{ a: "1", b: "2" }` matches both branches and each would parse a different key.

### extract / exclude

`.extract()` keeps the branches of a union that are assignable to a definition, and `.exclude()` removes them, like TypeScript's `Extract` and `Exclude`:

```ts
const Primitive = type("string | number | boolean")

// Type<number | boolean>
const NumberOrBoolean = Primitive.extract("number | boolean")

// Type<number | boolean>
const NotString = Primitive.exclude("string")
```

In a definition, use the `Extract` and `Exclude` [generics](https://arktype.io/docs/generics#keywords), e.g. `"Exclude<'a' | 'b' | 0, string>"`.

## Brand

A brand adds a type-only tag to a type, so the only values that satisfy it are those you validated with it.

**string**

```ts
const Even = type("(number % 2)#even")
type Even = typeof Even.infer

const good: Even = Even.assert(2)
// TypeScript: Type 'number' is not assignable to type 'Brand<number, "even">'
const bad: Even = 5
```

**fluent**

```ts
const Even = type.number.divisibleBy(2).brand("even")
type Even = typeof Even.infer

const good: Even = Even.assert(2)
// TypeScript: Type 'number' is not assignable to type 'Brand<number, "even">'
const bad: Even = 5
```

A brand changes nothing at runtime. The `Brand` type it infers is exported from `arktype`.

For more on branding in general, see [this article](https://www.learningtypescript.com/articles/branded-types) by [Josh Goldberg](https://github.com/joshuakgoldberg).

## Narrow

A narrow adds custom validation to a type. Return `true` to accept the value, or call `ctx.mustBe()` or `ctx.reject()` to reject it with a message. The [intro](https://arktype.io/docs/intro/adding-constraints#narrow) walks through an example.

**fluent**

```ts
const Palindrome = type("string").narrow(
	(s, ctx) => s === [...s].reverse().join("") || ctx.mustBe("a palindrome")
)

// ArkErrors: must be a palindrome
Palindrome("arktype")
```

**tuple**

```ts
const Palindrome = type([
	"string",
	":",
	(s, ctx) => s === [...s].reverse().join("") || ctx.mustBe("a palindrome")
])

// ArkErrors: must be a palindrome
Palindrome("arktype")
```

**args**

```ts
const Palindrome = type(
	"string",
	":",
	(s, ctx) => s === [...s].reverse().join("") || ctx.mustBe("a palindrome")
)

// ArkErrors: must be a palindrome
Palindrome("arktype")
```

`ctx.reject()` can also set the error's `path` and `actual`, e.g. to report a mismatch at the right key without printing a password:

```ts
const Form = type({
	password: "string",
	confirmPassword: "string"
}).narrow(
	(data, ctx) =>
		data.password === data.confirmPassword ||
		ctx.reject({
			expected: "identical to password",
			actual: "",
			path: ["confirmPassword"]
		})
)

// ArkErrors: confirmPassword must be identical to password
Form({ password: "arktype", confirmPassword: "artkype" })
```

If a narrow's return type is a type predicate, the `Type` infers it:

```ts
// Type<`ark${string}`>
const ArkString = type("string").narrow(
	(data, ctx): data is `ark${string}` =>
		data.startsWith("ark") || ctx.reject("a string starting with 'ark'")
)
```

The [traversal API](https://arktype.io/docs/traversal-api) documents everything `ctx` can do.

## Filter

`filter` is like `narrow`, but checks a type's **input** instead of its output. The difference matters when the type transforms its input:

- **`narrow`** checks the **output**, after morphs run
- **`filter`** checks the **input**, before morphs run

```ts
const ShortNumeric = type("string.numeric.parse").filter(
	// s is the input string, not the parsed number
	(s, ctx) => s.length <= 10 || ctx.reject("at most 10 characters")
)

// 123
ShortNumeric("123")

// ArkErrors: must be at most 10 characters
ShortNumeric("12345678901")
```

Like `narrow`, a type predicate returned by a filter is inferred, here as the type's input.

## Pipe

A pipe transforms data after it is validated, through one or more functions called **morphs**. The [intro](https://arktype.io/docs/intro/morphs-and-more) walks through examples.

**fluent**

```ts
// Type<(In: string) => Out<string>>
const TrimStart = type("string").pipe(str => str.trimStart())
```

**tuple**

```ts
// Type<(In: string) => Out<string>>
const TrimStart = type(["string", "=>", str => str.trimStart()])
```

**args**

```ts
// Type<(In: string) => Out<string>>
const TrimStart = type("string", "=>", str => str.trimStart())
```

A morph receives the validated value itself rather than a copy, so a morph that mutates its argument mutates the caller's data. ArkType's own transforms, like defaults, copy each object they change and share every untransformed value with the input, and input nothing transforms is returned as is. The exception is an instance of a builtin class, like a `Date`, `Map` or function, which keeps its state in internal slots and is transformed in place. [`mutatesInput`](https://arktype.io/docs/configuration#mutatesinput) writes transforms into the data instead.

```ts
const T = type({ a: "string.trim", b: { c: "string" } })
const input = { a: " x ", b: { c: "y" } }

const out = T.assert(input)

out === input // false
out.b === input.b // true
```

### To

A morph can return `ArkErrors` to fail validation, so a `Type` works as a morph: it validates the previous output. The `to` operator pipes to a definition without wrapping it in `type`:

**string**

```ts
// Type<(In: string) => To<number>>
const ParseEven = type("string.numeric.parse |> number % 2")

// ArkErrors: must be even
ParseEven("3")
```

**fluent**

```ts
// Type<(In: string) => To<number>>
const ParseEven = type("string.numeric.parse").to("number % 2")

// ArkErrors: must be even
ParseEven("3")
```

**tuple**

```ts
// Type<(In: string) => To<number>>
const ParseEven = type(["string.numeric.parse", "|>", "number % 2"])

// ArkErrors: must be even
ParseEven("3")
```

**args**

```ts
// Type<(In: string) => To<number>>
const ParseEven = type("string.numeric.parse", "|>", "number % 2")

// ArkErrors: must be even
ParseEven("3")
```

`.to("number % 2")` is the same as `.pipe(type("number % 2"))`.

### n-ary

`.pipe()` accepts any number of morphs and types. `type.pipe()` does the same without a `Type` to start from:

```ts
// Type<(In: string) => To<string>>
const TrimStartNonEmpty = type.pipe(
	type.string,
	s => s.trimStart(),
	type.string.atLeastLength(1)
)

// ArkErrors: must be non-empty
TrimStartNonEmpty("   ")
```

## Unit

A [literal](https://arktype.io/docs/primitives#number-literals) is the simplest way to allow one exact primitive value. To allow a value a string can't embed, like a `symbol`, use `type.unit` or `===`:

**fluent**

```ts
const mySymbol = Symbol()

const ExactValue = type.unit(mySymbol)
```

**tuple**

```ts
const mySymbol = Symbol()

const ExactValue = type(["===", mySymbol])
```

**args**

```ts
const mySymbol = Symbol()

const ExactValue = type("===", mySymbol)
```

## Enumerated

`type.enumerated` allows any of a list of values. With one value, it's the same as `type.unit`.

**fluent**

```ts
const mySymbol = Symbol()

const ExactValueFromSet = type.enumerated(1337, true, mySymbol)
```

**tuple**

```ts
const mySymbol = Symbol()

const ExactValueFromSet = type(["===", 1337, true, mySymbol])
```

**args**

```ts
const mySymbol = Symbol()

const ExactValueFromSet = type("===", 1337, true, mySymbol)
```

## valueOf

`type.valueOf` allows the values of a TypeScript `enum` or an enum-like object:

```ts
enum TsEnum {
	numeric = 1
}

// Type<TsEnum.numeric>
const EnumType = type.valueOf(TsEnum)
```

It is almost the same as `type.enumerated(...Object.values(o))`. The difference is an entry whose key is another entry's numeric value, mapping back to that entry's key. That's how TypeScript compiles a numeric `enum`, so `valueOf` skips the reverse entry:

```ts
// what TsEnum compiles to
const equivalentObject = {
	numeric: 1,
	"1": "numeric"
} as const

// allows only 1, though it infers Type<1 | "numeric">
const EquivalentType = type.valueOf(equivalentObject)
```

> **Prefer enumerated**
>
> TypeScript is moving away from features that emit JavaScript, like `enum`, which [`--erasableSyntaxOnly`](https://www.typescriptlang.org/tsconfig/#erasableSyntaxOnly) disallows. `type.valueOf` is for code that already uses `enum`. Otherwise, list values with [`type.enumerated`](https://arktype.io/docs/expressions#enumerated) or a literal union.

## fn

`type.fn` wraps a function so its parameters, and optionally its return value, are validated when it's called. Parameters use tuple syntax. Put a return type after `":"`.

```ts
const len = type.fn("string | unknown[]", ":", "number")(s => s.length)

len("foo") // 3
len([1, 2]) // 2

// TraversalError: [0] must be a string or an array
len(true)
// TypeScript: Argument of type 'boolean' is not assignable to parameter of type 'string | unknown[]'.
```

The result is a `TypedFn`, which is introspectable:

```ts
const len = type.fn("string | unknown[]", ":", "number")(s => s.length)

len.expression // "(string | Array) => number"
len.params.expression // "[string | Array]"
len.returns.expression // "number"
```

Parameters can be defaultable, optional or variadic:

```ts
const greet = type.fn("string = 'world'")(name => `Hello, ${name}!`)

greet() // "Hello, world!"

const join = type.fn("...", "string[]")((...parts) => parts.join(","))

join("a", "b") // "a,b"
```

Without a return type, the return type is inferred from the implementation and not validated.

## Meta

Metadata attaches information to a type. ArkType reads some of it, like `description`, which error messages use. You can read the rest from the type's `meta`.

**fluent**

```ts
const SpecialString = type("string").configure({
	description: "a special string"
})

// .describe() is shorthand for a description
const SpecialNumber = type("number").describe("a special number")

// ArkErrors: must be a special number
SpecialNumber("five")
```

**tuple**

```ts
const SpecialString = type([
	"string",
	"@",
	{
		description: "a special string"
	}
])

// a string is shorthand for a description
const SpecialNumber = type(["number", "@", "a special number"])

// ArkErrors: must be a special number
SpecialNumber("five")
```

**args**

```ts
const SpecialString = type("string", "@", {
	description: "a special string"
})

// a string is shorthand for a description
const SpecialNumber = type("number", "@", "a special number")

// ArkErrors: must be a special number
SpecialNumber("five")
```

An object definition can hold its own metadata under an `"@"` key:

```ts
const User = type({
	"@": "a user",
	name: "string"
})

// ArkErrors: must be a user
User(5)
```

A configured description, like any message you configure, takes precedence over the [locale](https://arktype.io/docs/i18n#your-own-messages), so it isn't translated.

The `keyword` key is reserved: built-in keywords set `meta.keyword` to their name so a locale can find their phrase, and configuring a description removes it. Name your own metadata something else.

To configure only some of a type's nodes, pass a selector after the metadata:

**fluent**

```ts
const Point = type({
	x: "number",
	y: "number"
}).configure(
	{ description: "a coordinate" },
	// every domain node: the object and both numbers
	"domain"
)

// ArkErrors: x must be a coordinate
Point({ x: "1", y: 2 })
```

**tuple**

```ts
const Point = type([
	{
		x: "number",
		y: "number"
	},
	"@",
	{ description: "a coordinate" },
	// every domain node: the object and both numbers
	"domain"
])

// ArkErrors: x must be a coordinate
Point({ x: "1", y: 2 })
```

**args**

```ts
const Point = type(
	{
		x: "number",
		y: "number"
	},
	"@",
	{ description: "a coordinate" },
	// every domain node: the object and both numbers
	"domain"
)

// ArkErrors: x must be a coordinate
Point({ x: "1", y: 2 })
```

Selectors are documented with [`select`](https://arktype.io/docs/internals/nodes#select).

## Cast

A cast changes how a `Type` is inferred without changing what it validates:

**string**

```ts
// any string, but the editor suggests "foo" and "bar"
type AutocompletedString = "foo" | "bar" | (string & {})

const MyObj = type({
	autocompletedString: "string" as type.cast<AutocompletedString>
})
```

**fluent**

```ts
// any string, but the editor suggests "foo" and "bar"
type AutocompletedString = "foo" | "bar" | (string & {})

const MyObj = type({
	autocompletedString: type.string.as<AutocompletedString>()
})
```

## Parenthetical

Operators have the same precedence as in TypeScript, and parentheses group them the same way:

```ts
// Type<{ stringOrNumbers: string | number[]; stringsOrNumbers: (string | number)[] }>
const Groups = type({
	stringOrNumbers: "string | number[]",
	stringsOrNumbers: "(string | number)[]"
})
```

## this

`this` references the root of the definition it's in, which makes the type recursive:

```ts
const DisappointingGift = type({
	label: "string",
	"box?": "this"
})

const out = DisappointingGift({
	label: "foo",
	box: { label: "bar", box: {} }
})

if (out instanceof type.errors) {
	// ArkErrors: box.box.label must be a string (was missing)
	console.error(out.summary)
} else {
	// narrowed inference to arbitrary depth
	console.log(out.box?.box?.label)
	// (property) label: string | undefined
}
```

In a scope, `this` is a `ParseError`. Reference the alias by name instead, as described in [cyclic types](https://arktype.io/docs/scopes#cyclic-types):

```ts
const types = scope({
	DisappointingGift: {
		label: "string",
		"box?": "DisappointingGift"
	}
}).export()
```

# Match

> Branch on the type of a value with ArkType definitions, like a type-safe switch statement.

`match` pairs ArkType definitions with handlers. It returns a function that runs the handler of the first case its input satisfies.

## Case record API

Each key is a definition and each value is a handler. The handler's parameter is inferred from its key:

```ts
import { match } from "arktype"

const toLabel = match({
	string: s => s,
	number: n => n.toFixed(2),
	bigint: b => `${b}n`,
	default: "assert"
})

toLabel("abc") // "abc"
toLabel(5) // "5.00"
toLabel(5n) // "5n"
// TraversalError: must be a string, a number or a bigint
toLabel(true)
```

Cases are checked in the order they are defined. A matcher is complete once it has a `default`.

## Default

`default` decides what happens to input that matches no case:

| `default` | Accepts | When no case matches |
| - | - | - |
| `"assert"` | `unknown` | throws a `TraversalError` |
| `"never"` | only input the cases accept | throws a `TraversalError` |
| `"reject"` | `unknown` | returns `ArkErrors` |
| a function | `unknown` | returns the function's result |

```ts
import { match } from "arktype"

const sizeOf = match({
	string: s => s.length,
	number: n => n,
	default: "reject"
})

// ArkErrors: must be a string or a number
sizeOf(true)
```

## Fluent API

`.case(definition, handler)` adds one case at a time, which is convenient for definitions that can't be written as a key. It can follow a case record or start a chain as `match.case(...)`. `.default(...)` completes the matcher:

```ts
import { match } from "arktype"

const sizeOf = match({
	string: s => s.length,
	number: n => n
})
	// any object with a numeric length
	.case({ length: "number" }, o => o.length)
	.default(() => 0)

sizeOf("abc") // 3
sizeOf({ name: "David", length: 5 }) // 5
sizeOf(null) // 0
```

## Input with `in`

`.in<T>()` sets the input type of a matcher: calling it with anything else is a type error, and each handler's parameter is narrowed from `T`. It does not validate at runtime.

`.in(definition)` takes a definition instead and validates input against it before any case runs:

```ts
import { match } from "arktype"

const half = match.in("number | string").match({
	number: n => n / 2,
	default: s => s
})

half(4) // 2
// ArkErrors: must be a number or a string
half(true)
// TypeScript: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.
```

## Properties with `at`

`.at(key)` matches cases against the value of one property. Each handler receives the whole object:

```ts
import { match } from "arktype"

type Data = { id: 1; count: number } | { id: 2; label: string }

const describe = match
	.in<Data>()
	.at("id")
	.match({
		1: o => `${o.count} items`,
		2: o => o.label,
		default: "assert"
	})

describe({ id: 1, count: 3 }) // "3 items"
describe({ id: 2, label: "two" }) // "two"
// TraversalError: id must be 1 or 2 (was missing)
describe({ count: 3 })
// TypeScript: Property 'id' is missing in type '{ count: number; }' but required in type '{ id: 1; count: number; }'.
```

`match.at(key, cases)` does the same in one call.

## String values with `strings`

`.strings(cases)` treats each key as a string value rather than a definition, so a key needs no quotes and `number` matches the string `"number"`. It follows `.in(...)` or `.at(key)`, and a key that isn't a possible value of the input is a type error. Its types are much cheaper to check than `.match` with quoted string literals:

```ts
import { match } from "arktype"

type Shape = { kind: "circle"; r: number } | { kind: "square"; side: number }

const area = match
	.in<Shape>()
	.at("kind")
	.strings({
		circle: c => Math.PI * c.r ** 2,
		square: s => s.side ** 2,
		default: "assert"
	})

area({ kind: "square", side: 2 }) // 4
```

## Scoped aliases

`match` resolves the same keywords as `type`. To match on your own aliases, use the `match` method of your [scope](https://arktype.io/docs/scopes):

```ts
import { scope } from "arktype"

const $ = scope({ Id: "string", Count: "number" })

const describe = $.match({
	Id: id => `user ${id}`,
	Count: n => `${n} users`,
	default: "assert"
})

describe("42") // "user 42"
```

# Codecs

> Pair a morph with its inverse to encode output back into input.

A Type with morphs decodes input into output. A codec is a morph with an inverse, so its output can also be encoded back into input.

## Defining a codec

`codec` takes an input definition, an output definition and a function for each direction. It comes from `arktype/codecs`, which installs encoding when imported, so an app that doesn't encode doesn't ship it. Without that import, reading `.encode` throws a `ParseError`:

```ts
import { codec } from "arktype/codecs"

const EpochMs = codec("number.integer", "Date", {
	decode: n => new Date(n),
	encode: d => d.getTime()
})

// Date
const date = EpochMs(0)
// 0
const ms = EpochMs.encode(date)
```

A codec is a Type. `.encode` is a Type too, from output to input, so it validates what it receives like any other Type:

```ts
// ArkErrors: must be a Date
const out = EpochMs.encode("0")
```

What `encode` returns is validated against the input definition, so encoding always produces something the codec can decode.

## Composition

Every Type has `.encode`, which inverts each of its morphs, so a codec encodes wherever it is nested: in objects, arrays and tuples, unions, intersections, pipes and cyclic scopes.

```ts
const Event = type({
	name: "string",
	at: EpochMs,
	"reminders?": EpochMs.array()
})

// { name: "launch", at: 0, reminders: [60000] }
const encoded = Event.encode({
	name: "launch",
	at: new Date(0),
	reminders: [new Date(60000)]
})
```

A Type without morphs encodes as itself.

## Defaults and unions

A defaulted key is always present in decoded output, so it is required when encoding:

```ts
const Settings = type({ since: EpochMs.default(0) })

// ArkErrors: since must be a Date (was missing)
const out = Settings.encode({})
```

A union encodes a value with a branch that accepts it, trying the branches without morphs first, so a value a branch would decode unchanged is encoded unchanged.

## Keywords

The parse keywords encode back to the string they parse: `string.date.parse`, `string.date.iso.parse` and `string.date.epoch.parse`, `string.numeric.parse`, `string.integer.parse`, `string.json.parse` and `string.url.parse`.

```ts
import "arktype/codecs"

const Event = type({
	at: "string.date.iso.parse",
	count: "string.integer.parse"
})

// { at: "1970-01-01T00:00:00.000Z", count: "5" }
const encoded = Event.encode({ at: new Date(0), count: 5 })
```

`string.trim`, `string.lower`, `string.upper`, `string.capitalize` and `string.normalize` encode a string already in their format as itself, and `object.json.stringify` encodes by parsing.

## Precompiling

[Precompiled](https://arktype.io/docs/precompile) Types encode too. The build precompiles each `codec` like any other Type, passing its `decode` and `encode` functions where you wrote them, and each `.encode` it sees read becomes an encoder of its own:

```ts
import { codec } from "arktype/codecs"

const EpochMs = codec("number.integer", "Date", {
	decode: n => new Date(n),
	encode: d => d.getTime()
})

export const Event = type({ at: EpochMs })

// precompiled to an encoder
export const encode = (event: unknown) => Event.encode(event)
```

A standalone build installs encoding itself, so `.encode` works there even if the program never imports `arktype/codecs`. A Type with a morph that has no inverse fails the build where its `.encode` is read, since arktype would throw there.

## Morphs without an inverse

Encoding is only possible if every morph has an inverse. Otherwise, accessing `.encode` throws a `ParseError`:

```ts
import "arktype/codecs"

const Length = type({ length: type("string").pipe(s => s.length) })

// ParseError: A morph must have an inverse to be encoded: (In: string) => Out<unknown>
Length.encode
```

# Scopes

> Define aliases that reference each other, then use them in definitions or export them as a module of Types.

A scope is a set of named definitions, called aliases, that can reference each other the same way they reference keywords like `string`. The `type` function you import from `arktype` is a method of ArkType's default scope.

## Defining a scope

Pass `scope` an object mapping alias names to definitions:

```ts
import { scope } from "arktype"

const $ = scope({
	Id: "string",
	User: { id: "Id", friends: "Id[]" },
	UsersById: { "[Id]": "User" }
})
```

Aliases are autocompleted and validated like built-in keywords. Write definitions inside a scope directly: wrapping one in `type(...)` fails, because `type` only knows built-in keywords (see [thunks](https://arktype.io/docs/scopes#thunks)).

`$.type` parses a definition that can reference the scope's aliases. Types created this way keep their scope, so chained methods can reference the aliases too:

```ts
const Group = $.type({ name: "string", members: "User[]" })

const OwnedGroup = Group.and({ ownerId: "Id" })
```

`$.match`, `$.declare`, `$.generic` and `$.fn` work like their counterparts on `type`, but also resolve the scope's aliases.

## Modules

`.export()` turns a scope into a `Module`, an object mapping each alias to its `Type`:

```ts
const types = $.export()

// ArkErrors: friends[1] must be a string
types.User({ id: "99", friends: ["7", 8, "9"] })
```

To get a single `Type`, use `$.resolve("User")`.

`type.module` defines a scope and exports it in one call:

```ts
const types = type.module({
	Id: "string",
	User: { id: "Id", friends: "Id[]" }
})
```

A `Module` can be spread into another scope to include all of its aliases. Pass names to `.export()` to include only those:

```ts
const numbers = scope({ Three: "3", Sixty: "60", No: "'no'" })

const superScope = scope({
	...$.export(),
	...numbers.export("Three", "Sixty"),
	Saiyan: { powerLevel: "number > 9000" }
})
```

## Cyclic types

Aliases can reference themselves and each other:

```ts
const types = scope({
	Package: {
		name: "string",
		"dependencies?": "Package[]",
		"contributors?": "Contributor[]"
	},
	Contributor: {
		email: "string.email",
		"packages?": "Package[]"
	}
}).export()
```

Cyclic types are inferred to any depth, and they validate cyclic data:

```ts
type Package = typeof types.Package.infer

const packageData: Package = {
	name: "arktype",
	dependencies: [{ name: "typescript" }],
	contributors: [{ email: "david@sharktypeio" }]
}

// arktype now depends on itself
packageData.dependencies![0].dependencies = [packageData]

// ArkErrors: contributors[0].email must be an email address
types.Package(packageData)
```

A cycle must pass through an object, array or morph. An alias that resolves to itself without one, like `a` in `scope({ a: "a | string" })`, is a type error and throws a `ParseError`.

For a single recursive `Type`, you don't need a scope: use the [`this`](https://arktype.io/docs/expressions#this) keyword.

> **Cyclic types may display as any**
>
> TypeScript shows an anonymous cycle as `...`, or as `any` if `noErrorTruncation` is enabled. Either way, the type itself is accurate: you get completions, and accessing a property that doesn't exist is an error.

## Visibility

Aliases prefixed with `#` are private. They can be referenced in the scope, but are not exported:

```ts
const shapes = scope({
	"#BaseShape": { perimeter: "number", area: "number" },
	// reference private aliases without the "#"
	Ellipse: { "...": "BaseShape", radii: ["number", "number"] },
	Rectangle: { "...": "BaseShape", width: "number", height: "number" }
})

// shapes.type can still reference private aliases
const PartialShape = shapes.type("Partial<BaseShape>")

const shapeModule = shapes.export()
Object.keys(shapeModule) // ["Ellipse", "Rectangle"]
```

### `import()`

`.import()` is like `.export()`, but makes every alias private. Spread it into a scope to use another scope's aliases without re-exporting them:

```ts
const utilities = scope({
	"WithId<o extends object>": { "...": "o", id: "string" }
})

const userModule = type.module({
	...utilities.import(),
	Payload: { name: "string", age: "number" },
	Db: "WithId<Payload>"
})

Object.keys(userModule) // ["Payload", "Db"]
```

## Submodules

Keywords like `string.email` are grouped into submodules. To group your own aliases, assign a `Module` to an alias and reference its members with a `.`:

```ts
const ids = type.module({ User: "string", Order: "number" })

const $ = scope({
	Id: ids,
	Customer: { id: "Id.User", orderIds: "Id.Order[]" }
})
```

Submodules are parsed bottom-up: the root scope can reference a submodule's aliases, but a submodule can't reference the root scope's aliases.

### Nested

Submodules can be nested to any depth:

```ts
const store = scope({ Store: $.export() })

const OrderIds = store.type("Store.Id.Order[]")
```

### Rooted

A submodule can't be referenced as a `Type` itself unless it has an alias named `root`, the way `string` is both a keyword and the prefix of `string.email`:

```ts
const userModule = type.module({
	root: { name: "string" },
	// subaliases can reference root like any other alias
	Admin: { "...": "root", isAdmin: "true" },
	Saiyan: { "...": "root", powerLevel: "number > 9000" }
})

const types = type.module({
	User: userModule,
	// User refers to the root alias
	Group: "User[]",
	// or prefixes its subaliases
	ElevatedUser: "User.Admin | User.Saiyan"
})
```

## Thunks

A common mistake is wrapping a scoped definition in `type`:

```ts
const $ = scope({
	Id: "string",
	User: type({
		name: "string",
		id: "Id"
		// TypeScript: 'Id' is unresolvable
	})
})
```

`Id` exists in the scope, but `type` only knows built-in keywords. Here the wrapper is redundant, so remove it:

```ts
const $ = scope({
	Id: "string",
	User: {
		name: "string",
		id: "Id"
	}
})
```

To use fluent methods like `.pipe` on a scoped definition, define it as a thunk: a function that calls the `type` method of the scope you're defining.

```ts
const $ = scope({
	Id: "string",
	TrimmedId: () => $.type("Id").pipe(s => s.trim())
})

const types = $.export()

types.TrimmedId("  42 ") // "42"
```

A thunk can't pass a callback that receives the data, like `.narrow`'s, to a Type that references the alias the thunk defines. TypeScript would read the callback's parameter from that alias, which is still being inferred from the thunk, and reports the thunk as implicitly `any`. Write the narrow as a tuple expression instead:

```ts
const $ = scope({
	File: { name: "string" },
	Directory: {
		name: "string",
		children: [
			"(File | Directory)[]",
			":",
			children => new Set(children.map(c => c.name)).size === children.length
		]
	}
})
```

## Configuration

`scope` takes a config as its second argument. It applies to every `Type` parsed in the scope:

```ts
const $ = scope({ Even: "number % 2" }, { divisor: { expected: "even" } })

// ArkErrors: must be even
$.export().Even(3)
```

It accepts the same options as [global configuration](https://arktype.io/docs/configuration), except these, which can only be configured globally: `onUndeclaredKey`, `numberAllowsNaN`, `numberAllowsInfinity`, `dateAllowsInvalid`, `keywords` and `locale`.

# Generics

> Declare definitions with parameters and instantiate them like TypeScript generics.

A generic is a definition with parameters. Instantiating it with a definition for each parameter returns a `Type`.

## Keywords

Like TypeScript's utility types, these generics are available in any definition:

| Alias | Description |
| - | - |
| `Exclude` | exclude branches of a union like \`Exclude("boolean", "true")\` |
| `Extract` | extract branches of a union like \`Extract("0 \| false \| 1", "number")\` |
| `Merge` | merge an object's properties onto another like \`Merge(User, { isAdmin: "true" })\` |
| `Omit` | omit a set of properties from an object like \`Omit(User, "age")\` |
| `Partial` | make all named properties of an object optional like \`Partial(User)\` |
| `Pick` | pick a set of properties from an object like \`Pick(User, "name \| age")\` |
| `Record` | instantiate an object from an index signature and corresponding value type like \`Record("string", "number")\` |
| `Required` | make all named properties of an object required like \`Required(User)\` |

Instantiate one in a string, or call it from `type.keywords`:

```ts
const One = type("Extract<0 | 1, 1>")

const Unfalse = type.keywords.Exclude("boolean", "false")
```

`Record` is also available as `type.Record`. Generics like `Pick` and `Partial` have [method equivalents](https://arktype.io/docs/objects#properties-pick-omit) on object Types, such as `User.pick("name")`.

## Syntax

### Definition

Pass a string of parameter names in angle brackets, then a definition that references them:

```ts
const BoxOf = type("<t>", { box: "t" })

// Type<{ box: string }>
const StringBox = BoxOf("string")
```

`type.generic("t")({ box: "t" })` is equivalent.

### Constraints

Constrain a parameter with `extends`. Arguments must satisfy the constraint, and the definition can use the parameter wherever its constraint is allowed, like with the `>` operator here:

```ts
const NonEmpty = type("<arr extends unknown[]>", "arr > 0")

// Type<number[]>
const NonEmptyNumbers = NonEmpty("number[]")

// ParseError: arr must be assignable to Array (was string)
NonEmpty("string")
// TypeScript: ["Invalid argument for arr", expected: unknown[]]
```

With `type.generic`, pass a `[name, constraint]` tuple: `type.generic(["arr", "unknown[]"])("arr > 0")`.

### Scoped

In a [scope](https://arktype.io/docs/scopes), declare parameters in the alias name:

```ts
const types = scope({
	"Box<t, u>": { box: "t | u" },
	BitBox: "Box<0, 1>"
}).export()

// ArkErrors: box must be 0 or 1
types.BitBox({ box: 2 })
```

### Recursive

A scoped generic can reference itself:

```ts
const types = scope({
	"Tree<t>": { value: "t", "children?": "Tree<t>[]" },
	NumberTree: "Tree<number>"
}).export()

// ArkErrors: children[0].value must be a number
types.NumberTree({ value: 1, children: [{ value: "2" }] })
```

## HKT

`generic()` with an `Hkt` class wraps a type-level TypeScript function as an ArkType generic. The function transforms the arguments at runtime, and the class's `body` describes the result at the type level. This is how `Partial` is implemented:

```ts
import { generic, Hkt } from "arktype"

const Partial = generic(["T", "object"])(
	args => args.T.partial(),
	class PartialHkt extends Hkt<[object]> {
		declare body: Partial<this[0]>
	}
)

// Type<{ a?: string }>
const PartialA = Partial({ a: "string" })
```

For more examples, see the [generic tests](https://github.com/arktypeio/arktype/blob/HEAD/ark/type/__tests__/generic.test.ts).

## External

To write a TypeScript function that accepts and returns Types, constrain a parameter with `type.Any`:

```ts
const createBox = <t extends string>(of: type.Any<t>) =>
	type({
		box: of
	})

// @ts-expect-error
createBox(type("number"))

// Type<{ box: string }>
const BoxType = createBox(type("string"))
```

To accept a definition instead, validate it with `type.validate` and infer the result with `type.instantiate`:

```ts
const createBox = <const def>(
	of: type.validate<def>
): type.instantiate<{ box: def }> =>
	type.raw({
		box: of
	}) as never

// Type<{ box: string }>
const BoxType = createBox("string")
```

TypeScript generics like these can be hard to get right. If yours isn't inferring as expected, see [the FAQ](https://arktype.io/docs/faq#why-isnt-my-wrapper-generic-working).

# Declare

> Define a Type that must match an existing TypeScript type exactly.

If your ArkType definitions are your source of truth, infer your TypeScript types from them: `type User = typeof User.infer`.

If the TypeScript type comes first, `type.declare` checks that a definition matches it. Object keys are autocompleted, and a definition that is too wide _or_ too narrow is a type error:

```ts
type Expected = { a: string; b?: number }

const T = type.declare<Expected>().type({
	a: "string",
	"b?": "number"
})

const Bad = type.declare<Expected>().type({
	a: "string",
	// narrower than number
	"b?": "1"
	// TypeScript: declared: number; inferred: 1;
})
```

Optionality can also be expressed in the value instead of the key:

```ts
type Expected = { a: string; b?: number }

const T = type.declare<Expected>().type({
	a: "string",
	// same as "b?": "number"
	b: "number?"
})
```

`declare` works with any definition, not only objects:

```ts
const Name = type.declare<string>().type("string")

const Entry = type.declare<[string, number]>().type(["string", "number"])
```

To reference your own aliases, use the `declare` method of your [scope](https://arktype.io/docs/scopes), like `$.declare<User>().type(...)`.

## `side`

A Type with morphs or defaults has different input and output types. For example, `string.numeric.parse` accepts a `string` and returns a `number`.

By default, `declare` compares your definition to the declared type as a whole, so a morph only matches if the declared type includes it. To compare only the input or output, pass `{ side: "in" }` or `{ side: "out" }`:

```ts
type Expected = { a: number; b?: number }

const Bad = type.declare<Expected>().type({
	a: "string.numeric.parse",
	// TypeScript: declared: number; inferred: (In: string) => To<number>;
	"b?": "number"
})

// the output must match Expected
const T = type.declare<Expected, { side: "out" }>().type({
	a: "string.numeric.parse",
	"b?": "number"
})
```

# Validation

> Check data against a Type by calling it, asserting it or testing it with allows.

## Calling a Type

A Type is a function. Call it with any data and it returns either the validated output or `ArkErrors`:

```ts
const User = type({
	name: "string",
	age: "number.integer >= 0"
})

const out = User({ name: "Alan", age: 41.5 })

if (out instanceof type.errors) {
	// age must be an integer
	console.error(out.summary)
} else {
	// out is { name: string; age: number }
	console.log(out.name)
}
```

`type.errors` is the `ArkErrors` class, so `instanceof` narrows the result. Invalid data never throws unless you configure [`onFail`](https://arktype.io/docs/configuration#onfail). See [Errors](https://arktype.io/docs/errors) for what `ArkErrors` contains.

The output is the data after [morphs](https://arktype.io/docs/intro/morphs-and-more) and defaults have run, so it can differ from the input:

```ts
const Form = type({ age: "string.numeric.parse" })

// { age: 41 }
Form({ age: "41" })

// ArkErrors: age must be a well-formed numeric string
Form({ age: "forty" })
```

## assert

`.assert` returns the output or throws a [`TraversalError`](https://arktype.io/docs/errors#traversalerror), for when invalid data is a bug rather than something to handle:

```ts
const Form = type({ age: "string.numeric.parse" })

// { age: 41 }
const form = Form.assert({ age: "41" })

// TraversalError: age must be a well-formed numeric string
Form.assert({ age: "forty" })
```

## from

`.from` is `.assert` with its argument typed as the Type's input, so TypeScript checks data you write by hand:

```ts
const User = type({ name: "string", age: "number" })

// { name: "David", age: 34 }
const david = User.from({ name: "David", age: 34 })

// TypeScript: Type 'string' is not assignable to type 'number'
const typo = User.from({ name: "David", age: "34" })
```

## allows

`.allows` returns a boolean and narrows its argument, without building errors or running morphs:

```ts
const User = type({ name: "string", age: "number" })

const data: unknown = { name: "David", age: 34 }

if (User.allows(data)) {
	// data is { name: string; age: number }
	console.log(data.name)
}

const Numeric = type("number | bigint")

// [0, 2n]
const numerics = [0, "one", 2n].filter(Numeric.allows)
```

On a Type with a morph, `.allows` checks only the input, so data can be allowed and still fail when the Type is called:

```ts
const AtLeast6 = type("string.numeric.parse").to("number >= 6")

// true, since "3" is a numeric string
AtLeast6.allows("3")

// ArkErrors: must be at least 6
AtLeast6("3")
```

## Standard Schema

Every Type implements [Standard Schema](https://arktype.io/docs/standard-schema), so libraries that accept one can validate with it through `~standard.validate`. ArkType validates synchronously, and a failure result is `{ issues }`, a copy of each error in the `ArkErrors` whose `message` [leaves out its path](https://arktype.io/docs/standard-schema#validation):

```ts
const User = type({ name: "string", age: "number" })

const result = await User["~standard"].validate({ name: "David", age: "34" })

if (result.issues) {
	// must be a number
	console.log(result.issues[0].message)
} else {
	// { name: string; age: number }
	console.log(result.value)
}
```

## Custom checks

To add your own check, use [`.narrow`](https://arktype.io/docs/expressions#narrow). To transform data, use [`.pipe`](https://arktype.io/docs/expressions#pipe). Both receive a [`ctx`](https://arktype.io/docs/traversal-api) for reporting errors.

# Errors

> Read, serialize and throw the errors a Type returns for invalid data.

## ArkErrors

A Type called with invalid data returns `ArkErrors`, which holds one error for each check that failed, in the order each failed:

```ts
import { flatProblemsByPath, type } from "arktype"

const User = type({
	name: "string",
	age: "number >= 0"
})

const out = User({ name: 5, age: -1 })

if (out instanceof type.errors) {
	// age must be non-negative
	// name must be a string
	console.error(out.summary)

	// ["age must be non-negative",
	//  "name must be a string"]
	out.issues.map(error => error.message)

	// { age: ["must be non-negative"],
	//   name: ["must be a string"] }
	flatProblemsByPath(out)
}
```

`ArkErrors` isn't an array. Its errors are in `issues`, so index them, iterate them or call array methods there.

| member | what it is |
| - | - |
| `issues` | an array with one error per failed check, in the order each failed |
| `summary`, `toString()` | every error's message, one per line |
| `count` | how many errors were added |
| `toJSON()` | an array of each error's JSON, with its `propString` |
| `toLocaleString(locale?)` | the summary in a [locale](https://arktype.io/docs/i18n#rendering-in-a-locale) |
| `throw()` | throws a [`TraversalError`](https://arktype.io/docs/errors#traversalerror) |

`arktype` exports functions that read an `ArkErrors`, most grouping it by path:

| function | what it returns |
| - | - |
| `firstIssue(out)` | the first error in `issues`, found [without the rest](https://arktype.io/docs/errors#finding-only-the-first) where it can be |
| `byPath(out)` | an object mapping each path's `propString` to its first error |
| `flatByPath(out)` | like `byPath`, but each value is an array of every error at the path |
| `flatProblemsByPath(out)` | like `flatByPath`, but with each error's `problem` |
| `byAncestorPath(out)` | each failed path and its ancestors, with `""` for the root, mapped to every error at or below it |
| `messageIn(error, locale)` | one error's message in a [locale](https://arktype.io/docs/i18n#rendering-in-a-locale) |

A Type that calls no narrow or morph may find its errors' issues only when they're first read, so rejecting data costs little more than the check that rejected it. The issues describe the data as it is at that read, not as it was validated: a write to it in between can change them, and data that no longer fails holds one root issue, `is invalid`. Read `summary` or `issues` before the data you validated can change, as it can when it's reactive form state or an Immer draft, or when an `await` comes before you report the errors:

```ts
const User = type({ name: "string" })
const form: Record<string, unknown> = { name: 5 }

const out = User(form)
// read now: name must be a string
const summary = out instanceof type.errors ? out.summary : ""

form.name = "Ada"
// read only now, out.summary would be "is invalid"
```

A getter or `Proxy` trap the check reads runs again at that read, and what it throws is thrown there. Each error's text is written at that first read too.

### Finding only the first

Where a form shows one error at a time, read it with `firstIssue`. Errors that haven't found their issues yet, like those of a Type that calls no narrow or morph or of a [precompiled](https://arktype.io/docs/precompile) validator, find only that one, reading the data until it fails, so the rest cost nothing until `issues` or `summary` is read:

```ts
import { firstIssue, type } from "arktype"

const User = type({ name: "string", age: "number >= 0" })

const out = User({ name: 5, age: -1 })

// age must be non-negative
if (out instanceof type.errors) console.error(firstIssue(out).message)
```

It's the error `issues[0]` holds. Unlike [`errors: "first"`](https://arktype.io/docs/configuration#errors), it leaves the rest to be found, and it's the first a full validation finds, not whichever is cheapest.

## ArkError

Each error in `issues` is a plain object, typed as `ArkError`, describing what failed at one path:

```ts
const out = type({ age: "number >= 0" })({ age: -1 })

if (out instanceof type.errors) {
	const error = out.issues[0]

	error.code // "min"
	error.path // ["age"]
	error.propString // "age"
	error.data // -1
	error.expected // "non-negative"
	error.actual // "-1"
	error.problem // "must be non-negative"
	error.message // "age must be non-negative"

	// narrow by code to read its own fields
	if (error.code === "min") error.rule // 0
}
```

Its message is built from parts: `message` puts the path before `problem`, which reads "must be `expected`". It doesn't say what the value was, which `data` holds and `actual` describes, like "-1" or "a string", unless an [`actual`](https://arktype.io/docs/configuration#actual) is configured, written as "(was `actual`)"; a missing key's reads "must be a string (was missing)". A union's `problem` writes the path of each error it lists from its own, and its `message` writes them whole. You can [configure each part](https://arktype.io/docs/configuration#error-messages).

An error also has `meta`, the metadata of the Type that failed, and usually a `description`. It has no methods, so `JSON.stringify(error)` serializes its own keys, and `messageIn(error, locale)` writes its message in another locale.

When several checks fail at one path, each is its own error. `flatByPath` and `flatProblemsByPath` group them by path:

```ts
import { flatProblemsByPath, type } from "arktype"

const out = type({ n: "number % 2 >= 2" })({ n: 1 })

if (out instanceof type.errors) {
	// n must be even
	// n must be at least 2
	console.error(out.summary)

	// { n: ["must be even", "must be at least 2"] }
	flatProblemsByPath(out)
}
```

## Error codes

An error's `code` tells you its other fields:

| code | fields |
| - | - |
| `domain` | `domain`, like `"string"` |
| `unit` | `unit`, the expected value |
| `proto` | `proto`, the expected constructor |
| `min`, `max` | `rule`, and `exclusive` when the bound is exclusive |
| `minLength`, `maxLength`, `exactLength` | `rule` |
| `divisor` | `rule` |
| `pattern` | `rule` (the regex source) and `flags` |
| `before`, `after` | `rule`, a `Date` |
| `notEqual` | `rule`, a number or `Date` |
| `notEqualLength` | `rule` |
| `predicate` | `predicate` when a narrow returns `false`; `morph` and what it threw as `cause` for `pipe.try`; `meta.keyword` and sometimes `cause` for a keyword's parse |
| `required` | `missing`, the missing value's type; `valueMeta`, its meta; and `missingValueDescription`, its English description |
| `undeclared` | none; its `data` is the value of a key `"+": "reject"` disallows |
| `discriminant` | `discriminantKind`, `cases`, `onKey` and `absent` |
| `union` | `errors`, one per branch, or none where each branch fails at what it is, like `Date \| RegExp` given `1`, which expects `a Date or a RegExp` |

Each also has `data` and `path`, and `meta` unless `ctx` or `pipe.try` raised it. Built-in keywords with their own text, like `string.email`, set `meta.keyword` to their name.

`discriminant` is a miss of a union ArkType checks by switching on a domain or a literal value: branches with different domains, like `number | null`, two or more literals, like `boolean` or `"a" | "b"`, or objects with a discriminant key. Its `data` is the discriminant's value, and `cases` lists the values or domains it expected, with `"Array"` in place of `"object"` where every object it expected is an array:

```ts
const Shape = type({ kind: "'circle'", r: "number" }).or({
	kind: "'square'",
	side: "number"
})

const out = Shape({ kind: "triangle" })

if (out instanceof type.errors) {
	const error = out.issues[0]

	// kind must be "circle" or "square"
	error.message

	// ["circle", "square"]
	if (error.code === "discriminant") error.cases
}
```

A union reports `union` instead where its discriminant can't tell the branches apart: an undiscriminated union; data that can't hold the discriminant, like `5` for a union of objects; and data matching none of the discriminant's values when some branches don't have its key, whose `errors` hold the miss beside those branches' errors.

## TraversalError

`.assert`, `.from` and `ArkErrors`' `throw()` throw a `TraversalError`, which extends `Error`. Its message is the errors' summary, one line per error:

```ts
import { flatProblemsByPath, type, TraversalError } from "arktype"

try {
	type({ a: "string", b: "number" }).assert({ a: 1, b: "x" })
} catch (e) {
	if (e instanceof TraversalError) {
		// "a must be a string\nb must be a number"
		e.message

		// the ArkErrors, for structured access
		flatProblemsByPath(e.arkErrors)
	}
}
```

`arkErrors` is non-enumerable, so loggers that print an error's own properties skip it.

## ParseError

A `ParseError` is thrown when a definition is invalid, as the Type is created rather than when it validates. TypeScript reports the same mistakes in your editor, so you'll usually see one only for definitions TypeScript can't check, like strings built at runtime:

```ts
import { ParseError, type } from "arktype"

const def: string = "string | numbr"

try {
	type.raw(def)
} catch (e) {
	// ParseError: 'numbr' is unresolvable
	if (e instanceof ParseError) console.error(e.message)
}
```

# Traversal API

> The ctx argument that narrow and pipe functions receive for reading the current path and reporting errors.

Functions you pass to [`.narrow`](https://arktype.io/docs/expressions#narrow) and [`.pipe`](https://arktype.io/docs/expressions#pipe) receive a `ctx` as their second argument. Use it to report errors that read like ArkType's own:

```ts
const Even = type("number").narrow(
	(n, ctx) => n % 2 === 0 || ctx.mustBe("even")
)

// ArkErrors: must be even
Even(3)
```

A narrow returns `ctx.mustBe(...)` or `ctx.reject(...)`, which add an error and return `false`. A morph returns `ctx.error(...)`, which adds an error and returns it:

```ts
const Json = type("string").pipe((s, ctx) => {
	try {
		return JSON.parse(s)
	} catch {
		return ctx.error("valid JSON")
	}
})

// ArkErrors: must be valid JSON
Json("{")
```

`reject` and `error` take a string or the parts of an error. `relativePath` reports it below the current path:

```ts
const Range = type({ start: "number", end: "number" }).narrow(
	(range, ctx) =>
		range.start <= range.end ||
		ctx.reject({
			expected: "at least start",
			actual: `${range.end}`,
			relativePath: ["end"]
		})
)

// ArkErrors: end must be at least start (was 1)
Range({ start: 2, end: 1 })
```

To write a check outside the call, type `ctx` with `Traversal`:

```ts
import { type, type Traversal } from "arktype"

const isEven = (n: number, ctx: Traversal) => n % 2 === 0 || ctx.mustBe("even")

const Even = type("number").narrow(isEven)
```

## Members

### `path`

the path being validated or morphed

- array indices represented as numbers
- warning: mutated during traversal - use `path.slice(0)` to snapshot
- use [`propString`](https://arktype.io/docs/traversal-api#propstring) for a stringified version

### `root`

the original value being traversed

### `config`

configuration for this traversal

- options can affect traversal results and error messages
- defaults < global config < scope config
- does not include options configured on individual types

### `hasError`

whether `currentBranch` (or the traversal root, outside a union) has one or more errors

### `errors`

[ArkErrors](https://arktype.io/docs/errors) that will be part of this traversal's finalized result

- will always be empty for a valid traversal

### `data`

the data being validated or morphed

- the value at [`path`](https://arktype.io/docs/traversal-api#path), as transformed by any morphs that have already run

### `propString`

a string representing [`path`](https://arktype.io/docs/traversal-api#path)

- uses `.access` [where allowed by JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#dot_notation), falling back to `[indexAccess]`

```ts
const path = ["key1", Symbol("key2"), "key3", 4, "~key5"]
const propString = 'key1[Symbol(key2)].key3[4]["~key5"]'
```

### `reject`

add an [ArkError](https://arktype.io/docs/errors) and return `false`

- useful for predicates like `.narrow`

### `mustBe`

add an [ArkError](https://arktype.io/docs/errors) from a description and return `false`

- useful for predicates like `.narrow`
- equivalent to [`reject`](https://arktype.io/docs/traversal-api#reject)({ expected })

### `error`

add and return an [ArkError](https://arktype.io/docs/errors)

- useful for morphs like `.pipe`

# Configuration

> 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:

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

configure({ numberAllowsNaN: true })
```

```ts
import "./config.ts"
import { type } from "arktype"

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

> **Configure 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"`.

### Scope

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

```ts
const $ = scope(
	{ User: { age: "number < 100" } },
	{ max: { actual: () => "unacceptably large" } }
)

// ArkErrors: age must be less than 100 (was unacceptably large)
$.export().User({ age: 101 })

// ArkErrors: age must be at most 100 (was unacceptably large)
$.type({ age: "number <= 100" })({ age: 101 })
```

### Type

`.configure` adds [metadata](https://arktype.io/docs/expressions#meta), like a `description` or [error parts](https://arktype.io/docs/configuration#error-messages), to a Type. It applies wherever that Type is referenced, but not to the Types inside it:

```ts
// don't print the password
const Password = type("string >= 8").configure({ actual: "" })

const User = type({
	email: "string.email",
	password: Password
})

// ArkErrors: password must be at least length 8
User({ email: "david@arktype.io", password: "ez123" })
```

## Options

| option | default | levels |
| - | - | - |
| [`onUndeclaredKey`](https://arktype.io/docs/configuration#onundeclaredkey) | `"ignore"` | global, type (`"+"`) |
| [`exactOptionalPropertyTypes`](https://arktype.io/docs/configuration#exactoptionalpropertytypes) | `true` | global, scope |
| [`numberAllowsNaN`](https://arktype.io/docs/configuration#numberallowsnan) | `false` | global |
| [`numberAllowsInfinity`](https://arktype.io/docs/configuration#numberallowsinfinity) | `false` | global |
| [`dateAllowsInvalid`](https://arktype.io/docs/configuration#dateallowsinvalid) | `false` | global |
| [`jitless`](https://arktype.io/docs/configuration#jitless) | `false`, or `true` where `new Function` is blocked | global, scope |
| [`onFail`](https://arktype.io/docs/configuration#onfail) | `null`, which returns `ArkErrors` | global, scope |
| [`errors`](https://arktype.io/docs/configuration#errors) | `"all"` | global, scope |
| [`mutatesInput`](https://arktype.io/docs/configuration#mutatesinput) | `false` | global, scope |
| [`keywords`](https://arktype.io/docs/configuration#keywords) | `{}` | global |
| [`locale`](https://arktype.io/docs/configuration#locale) | `en` | global |
| [an error code](https://arktype.io/docs/configuration#by-code), like `divisor` | ArkType's messages | global, scope |
| [`toJsonSchema`](https://arktype.io/docs/configuration#tojsonschema) | draft 2020-12, throwing for what it can't express | global, scope |

A Type's own options are its [metadata](https://arktype.io/docs/expressions#meta), including the [parts of its errors](https://arktype.io/docs/configuration#error-messages).

## Error messages

Each error message is built from parts. Configure the part you want to change, and ArkType keeps composing the rest, including messages for unions and intersections. `expected`, `actual`, `problem` and `message` each take a string or a function. See [Errors](https://arktype.io/docs/errors) for what an error contains.

### description

What follows "must be" in a message. Other parts and the Type's `.description` reuse it, so it should be your first choice:

```ts
const Even = type("number % 2").describe("an even number")

// ArkErrors: must be an even number
Even(3)
```

### 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`:

```ts
const 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 goes inside "(was …)". A message doesn't say what the value was unless an `actual` is configured, except a missing key's, which reads "(was missing)", though an error's `actual` still describes its data, like "5" or "an object", for a `problem` or `message` you write. An empty string omits it. A function receives the data, then the error:

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

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

### problem

The whole sentence after the path, like "must be a string", and the text a [Standard Schema](https://arktype.io/docs/standard-schema) consumer, like a form library, shows beside a field as its issue's `message`. A union's problem lists each branch's path from its own. A function receives the error, including its `expected` and `actual`. It may not apply to the errors of a union:

```ts
const Name = type("string").configure({
	problem: ctx => `isn't ${ctx.expected}`
})

// ArkErrors: isn't a string
Name(5)
```

### message

The whole message, including the path, read from the errors calling a Type returns, their `summary` and what `.assert()` throws. It doesn't reach Standard Schema issues, whose `message` is the [`problem`](https://arktype.io/docs/configuration#problem). A function receives the error, including its `problem`. It may not apply to the errors of a union:

```ts
const User = type({
	password: "string >= 8"
}).configure({
	message: ctx => `${ctx.propString || "(root)"}: ${ctx.problem}`
})

// ArkErrors: (root): must be an object
User("ez123")

// .configure applies only at the root, so the nested error is unchanged
// ArkErrors: password must be at least length 8
User({ password: "ez123" })
```

Each function also receives the active [locale](https://arktype.io/docs/i18n#your-own-messages) as its last argument, so it can write its text in the language a message is read in.

### By code

Globally or in a scope, configure errors by their [code](https://arktype.io/docs/errors#error-codes). A function's `ctx` is typed by its code:

```ts
const mod = type.module(
	{ isEven: "number % 2" },
	{
		divisor: {
			expected: ctx => `% ${ctx.rule} !== 0`,
			problem: ctx => `${ctx.actual} ${ctx.expected}`
		}
	}
)

// ArkErrors: 3 % 2 !== 0
mod.isEven(3)
```

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

```ts
const $ = scope(
	{ User: { "+": "reject", name: "string" } },
	{ undeclared: { problem: "isn't allowed" } }
)

// ArkErrors: age isn't allowed
$.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:

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

configure({ locale: de })
```

```ts
import "./config.ts"
import { type } from "arktype"

// ArkErrors: muss eine Zeichenkette sein, ist aber eine Zahl
type.string(5)
```

`locale` can also be a function that returns a locale each time a message is read. See [i18n](https://arktype.io/docs/i18n).

## keywords

Configure built-in keywords like `string.email` by name. Each takes a description or the same options as [`.configure`](https://arktype.io/docs/configuration#type):

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

configure({
	keywords: {
		string: "text",
		"string.email": {
			actual: () => "definitely fake"
		}
	}
})
```

```ts
import "./config.ts"
import { type } from "arktype"

const 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" })
```

## 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 [`"+"`](https://arktype.io/docs/objects#properties-undeclared), or change the default globally:

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

configure({ onUndeclaredKey: "delete" })
```

```ts
import "./config.ts"
import { type } from "arktype"

const UserForm = type({
	name: "string"
})

// { name: "Alice" }
UserForm({ name: "Alice", age: "42" })
```

## exactOptionalPropertyTypes

By default, ArkType treats optional keys as TypeScript does with [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig/#exactOptionalPropertyTypes): an optional key can be omitted, but not set to `undefined`.

```ts
const 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:

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

configure({ exactOptionalPropertyTypes: false })
```

```ts
import "./config.ts"
import { type } from "arktype"

const MyObj = type({
	"key?": "number",
	withDefault: "number = 5"
})

// { key: undefined, withDefault: 5 }
MyObj({ key: undefined, withDefault: undefined })
```

With `false`, an explicit `undefined` at a key with a default is replaced by the default, as a missing key is. Treating `null` as missing is tracked in [#1283](https://github.com/arktypeio/arktype/issues/1283).

## numberAllowsNaN

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

```ts
const 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:

```ts
const 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`:

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

configure({ dateAllowsInvalid: true })
```

```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 up to about 30x slower per call on a plain object, and 3x to 5x on invalid data or a morph.

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](https://arktype.io/docs/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`:

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

configure({ jitless: true })
```

```ts
import "./config.ts"
import { type } from "arktype"

// will not be compiled
const 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](https://arktype.io/docs/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`

```ts
import { configure } from "arktype/config"
import "arktype/errors"

configure({ errors: "none" })
```

```ts
import "./config.ts"
import { type } from "arktype"

const User = type({ name: "string", age: "number" })

// ArkErrors: is invalid
const 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. It's still an instance of `type.errors`, `.assert()` throws a `TraversalError` saying `is invalid`, and its message isn't [localized](https://arktype.io/docs/configuration#locale). 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 to that Scope's Types, including where another Scope references them.

A [precompiled](https://arktype.io/docs/precompile/options#errors) 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

```ts
import { configure } from "arktype/config"
import "arktype/mutatesInput"

configure({ mutatesInput: true })
```

```ts
import "./config.ts"
import { type } from "arktype"

const User = type({ name: "string.trim", role: "string = 'member'" })

const data = { name: " Ada " }

// true, and data is now { name: "Ada", role: "member" }
const isData = Object.is(User(data), 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](https://arktype.io/docs/precompile/options#mutatesinput) build takes `mutatesInput` as an option.

## onFail

To throw on every failed validation, or transform its result some other way, configure `onFail`. Declare its return type on `ArkEnv` so calls are typed to match:

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

const config = configure({
	onFail: errors => errors.throw()
})

declare global {
	interface ArkEnv {
		onFail: typeof config.onFail
	}
}
```

```ts
import "./config.ts"
import { type } from "arktype"

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

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

`onFail` can also be passed to a scope.

## toJsonSchema

`toJsonSchema` sets the defaults for `.toJsonSchema()`, like its target and how to handle what JSON Schema can't express. See [JSON Schema](https://arktype.io/docs/json-schema/to-json-schema).

## metadata

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

```ts
// add this anywhere in your project
declare global {
	interface ArkEnv {
		meta(): {
			// meta properties should always be optional
			secretIngredient?: string
		}
	}
}

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

## 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:

```ts
declare global {
	interface ArkEnv {
		prototypes(): MySpecialClass
	}
}

class MySpecialClass {}

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

# i18n

> Write ArkType's error messages in another language, per app or per request.

ArkType's error messages can be written in any language. A locale supplies their text, and ArkType ships two: `en`, the default, and `de`.

## Configuring a locale

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

configure({ locale: de })
```

```ts
import "./config.ts"
// import your config file before arktype
import { type } from "arktype"

const User = type({
	name: "string >= 2",
	email: "string.email"
})

const out = User({ name: "A", email: "x" })

if (out instanceof type.errors) {
	// email muss eine E-Mail-Adresse sein, ist aber "x"
	// name muss mindestens 2 Zeichen lang sein, ist aber 1 Zeichen lang
	console.log(out.summary)
}
```

Like other [global config](https://arktype.io/docs/configuration#global), a locale is configured before any Type is created. It can't be set for a scope or a Type. To choose one per request, configure a [function](https://arktype.io/docs/i18n#switching-locales).

Shipped locales like `arktype/locales/de` work when imported. A locale you write, or a locale function, also needs `import "arktype/i18n"` unless a shipped locale is imported. Without it, creating a Type, `toLocaleString` or `messageIn` with that locale throws. This keeps other locales out of bundles that only use `en`.

Only an error's message and its parts, `expected`, `actual` and `problem`, are localized. A Type's `description` and `expression`, JSON Schema, an error's `description` and `ParseError`s stay in English.

## Labels

A locale may name a value by its `title`. `en` ignores titles, while `de` makes them the subject of the sentence:

```ts
const Signup = type({
	name: type("string >= 2").configure({ title: "Name" })
})

// with de: „Name“ muss mindestens 2 Zeichen lang sein, ist aber 1 Zeichen lang
const out = Signup({ name: "A" })
```

## Switching locales

`locale` can also be a function, called when an `ArkErrors`' messages are first read rather than when validation fails, so errors follow your app's language even if it changed after they were created:

```ts
import type { Locale } from "arktype"
import { configure } from "arktype/config"
import { de } from "arktype/locales/de"
import { en } from "arktype/locales/en"

const locales: Record<string, Locale> = { de, en }

let language = "en"

export const setLanguage = (next: string) => {
	language = next
}

configure({ locale: () => locales[language] })
```

On a server, the function can read the locale of the current request:

```ts
import type { Locale } from "arktype"
import { configure } from "arktype/config"
import "arktype/i18n"
import { AsyncLocalStorage } from "node:async_hooks"

export const requestLocale = new AsyncLocalStorage<Locale>()

configure({ locale: () => requestLocale.getStore() })
```

```ts
import { requestLocale } from "./config.ts"
import { type } from "arktype"
import { de } from "arktype/locales/de"

const User = type({ name: "string" })

const handle = (body: unknown) =>
	requestLocale.run(de, () => {
		const out = User(body)
		// name muss eine Zeichenkette sein, ist aber eine Zahl
		if (out instanceof type.errors) return { status: 400, error: out.summary }
		return { status: 200, user: out }
	})
```

The function is called once for an `ArkErrors`, whose messages keep the locale it returned, so they never mix languages. If it returns `undefined` or throws, they're written in English.

Since messages are written when they're first read, read `summary` or `issues` inside the request. Errors returned from `requestLocale.run` and read later, like by a framework's error handler, are written in English. There, call [`toLocaleString`](https://arktype.io/docs/i18n#rendering-in-a-locale) instead.

## Rendering in a locale

An `ArkErrors`' `toLocaleString` writes its summary in a locale of your choice, whatever locale is configured, and `messageIn` writes one error's message:

```ts
import { messageIn, type } from "arktype"
import { de } from "arktype/locales/de"

const out = type({ name: "string" })({ name: 5 })

if (out instanceof type.errors) {
	// name muss eine Zeichenkette sein, ist aber eine Zahl
	out.toLocaleString(de)
	messageIn(out.issues[0], de)
	// name must be a string
	out.issues[0].message
}
```

Called without a locale, `toLocaleString` returns the summary as configured.

## Your own messages

Any message you configure outranks the locale, which only writes what you leave out. That includes `.describe()`, `.configure()`, descriptions configured for [keywords](https://arktype.io/docs/configuration#keywords) and [errors configured by code](https://arktype.io/docs/configuration#by-code) in a scope or globally.

A string is shown as written in every locale. Since it may be in any language, `de` cites it rather than placing it bare in a German sentence:

```ts
const Password = type("string >= 8").describe("a secure password")

// with de: muss ein Wert gemäß der Beschreibung „a secure password“ sein, ist aber 2 Zeichen lang
const out = Password("ez")
```

If your descriptions are already German, `{ ...de, cite: text => text }` places them as written. To translate them, look each one up in `cite`, returning what follows the locale's "must be", as `de.cite` does:

```ts
import type { Locale } from "arktype"
import { configure } from "arktype/config"
import { de } from "arktype/locales/de"

const translations: Record<string, string> = {
	"a secure password": "ein sicheres Passwort"
}

const deTranslated = {
	...de,
	cite: text => translations[text] ?? de.cite(text)
} satisfies Locale.Complete

// Password("ez"): muss ein sicheres Passwort sein, ist aber 2 Zeichen lang
configure({ locale: deTranslated })
```

You can also translate your own text by writing it as a function. Every error writer you configure receives the active locale's `tag`, `list`, `plural`, `number`, `date` and `verbatim` as its last argument:

```ts
const Password = type("string >= 8").configure({
	expected: (ctx, locale) =>
		locale.tag === "de" ? "ein sicheres Passwort" : "a secure password"
})

// with de: muss ein sicheres Passwort sein, ist aber 2 Zeichen lang
const out = Password("ez")
```

A writer's text isn't cited, so it should read as what follows the locale's "must be", like `de`'s `muss … sein`. The writer can also call an [i18n library](https://arktype.io/docs/i18n#using-an-i18n-library).

## Changing part of a locale

A locale is an object, so you can spread it and replace what you'd like to change:

```ts
import type { Locale } from "arktype"
import { configure } from "arktype/config"
import { de } from "arktype/locales/de"

const deCompact = {
	...de,
	minLength: {
		...de.minLength,
		problem: ctx => `ist zu kurz (mindestens ${ctx.rule})`
	}
} satisfies Locale.Complete

configure({ locale: deCompact })
```

```ts
import "./config.ts"
// import your config file before arktype
import { type } from "arktype"

// ArkErrors: ist zu kurz (mindestens 3)
const out = type("string >= 3")("ab")
```

Spreading `de.minLength` keeps its `expected`, the fragment that unions and intersections list, like `mindestens 3 Zeichen lang`.

## Writing a locale

For a language ArkType doesn't ship, start from `en` and replace each part:

| part | writes |
| - | - |
| `tag` | the locale's BCP 47 language tag |
| `list` | a list of items joined by "or" or "and" |
| `plural` | the plural category of a number, like `"one"` or `"other"` |
| `number`, `date` | a number or a `Date` |
| `verbatim` | text shown as written, like paths and printed values |
| `cite` | expected text you wrote yourself, like a description |
| `nouns` | the name of each type, like "a string" |
| `basis` | one alternative of a missing key's value |
| `keywordPhrases` | the expected text of each keyword, like `"string.email"`, keyed by its name |
| `actual`, `message` | each part of a message, for every code that doesn't write it |
| `problem` | the sentence for a keyword's phrase or for expected text you wrote |
| `domain`, `min`, `required`, ... | one entry per [error code](https://arktype.io/docs/errors#error-codes) with its `problem` and optionally its `expected`, `actual` or `message` |

Each code's `problem` is a whole sentence without a subject, and `message` places the path or label before it. A code's `expected` is a fragment that unions and intersections list. A fragment reads as what follows the locale's "must be", like `fr`'s `doit être`:

```ts
import type { Locale } from "arktype"
import { listPattern } from "arktype/i18n"
import { en } from "arktype/locales/en"

const was = (actual: string) => actual && ` (reçu ${actual})`

const atLeast: Locale.ExpectedWriter<"min"> = (ctx, locale) =>
	`${ctx.exclusive ? "supérieur à" : "au moins"} ${locale.number(ctx.rule)}`

export const fr: Locale = {
	...en,
	tag: "fr",
	list: listPattern(
		{ two: " ou ", middle: ", ", end: " ou " },
		{ two: " et ", middle: ", ", end: " et " }
	),
	cite: text => `une valeur conforme à la description « ${text} »`,
	// for keyword phrases and text you wrote
	problem: ctx => `doit être ${ctx.expected}${was(ctx.actual)}`,
	// every subject is masculine, so "supérieur" agrees with it
	message: ctx =>
		ctx.path.length ? `le champ ${ctx.propString} ${ctx.problem}` : ctx.problem,
	min: {
		expected: atLeast,
		problem: (ctx, locale) =>
			`doit être ${atLeast(ctx, locale)}${was(ctx.actual)}`
	}
	// ...
}
```

- Until you replace them, the parts you spread from `en` write English. Most of its writers don't read `nouns`, `list` or `date`: only its `discriminant`, `required` and `union` writers and `basis` read `nouns`, and `required` and `union` also read `list`.
- Where a locale has no `expected` for a code, an error's `expected`, and so its `toJSON()`, is English. If your unions list their branches' fragments, annotate the locale with `Locale.Complete` to check that it has a fragment for every code and a phrase for every keyword. A locale without fragments can write its unions from `ctx.errors`, each with its own `problem`.
- A locale's writers receive the error and the locale. An error's `description` is English, so `expected` writers can't use it.
- `arktype/i18n` exports the helpers `de` is written with: `listPattern`, `isolate`, `groupByPath` (a union's errors by path), `labelOf` (the title of the value an error is about), `describeMissing`, `describeCause` and `writeKeywordExpected`.

Languages unlike English need a few more rules:

- `problem` has no subject, so where a predicate agrees with its subject, as in Russian, Polish or Arabic, `message` should give every subject one gender and number, like ru `Поле`/`Значение`, pl `Pole` or ar `الحقل`/`العنصر`. Particles go there too, like ja `nameは`.
- `cite`, `nouns`, `basis`, keyword phrases and fragments all read as what follows "must be", so they take its case, like the instrumental `строкой` after ru `должно быть`. Where an actual takes another case, like the nominative after ru `получено:`, write `actual` with its own forms.
- A title reaches `message` as written. Translate it there, in the form a subject takes.
- A right-to-left locale sets `verbatim: isolate`, so each path, value and name keeps its direction, in lists too.

## Using an i18n library

ArkType doesn't depend on an i18n library, but a locale's writers can call one, so you can keep ArkType's sentences in your own catalog under your own keys:

```ts
import type { Locale } from "arktype"
import { listPattern } from "arktype/i18n"
import { en } from "arktype/locales/en"
import i18next from "i18next"
import * as m from "./paraglide/messages.js"

// a namespace for ArkType's keys; escapeValue false, since messages aren't HTML
const t = (key: string, params?: object) =>
	i18next.t(key, {
		ns: "validation",
		lng: "fr",
		interpolation: { escapeValue: false },
		...params
	})

// a sentence, then the actual unless it's been suppressed
const was = (problem: string, actual: string) =>
	actual ? t("was", { problem, actual }) : problem

export const fr: Locale = {
	...en,
	tag: "fr",
	list: listPattern(
		{ two: " ou ", middle: ", ", end: " ou " },
		{ two: " et ", middle: ", ", end: " et " }
	),
	problem: ctx => was(t("mustBe", { expected: ctx.expected }), ctx.actual),
	min: {
		...en.min,
		// through locale.number, the rule is printed like the actual
		problem: (ctx, locale) =>
			was(
				t(ctx.exclusive ? "moreThan" : "min", {
					rule: locale.number(ctx.rule)
				}),
				ctx.actual
			)
	},
	// Paraglide: each message is a typed function
	required: { ...en.required, problem: () => m.required({}, { locale: "fr" }) }
}
```

With `"min": "doit être au moins {{rule}}"`, `"moreThan": "doit être supérieur à {{rule}}"` and `"was": "{{problem}} (reçu {{actual}})"` in the `validation` namespace, `type({ n: "number >= 2.5" })` reads `n doit être au moins 2.5 (reçu 1.5)` for `{ n: 1.5 }` and `n est requis` for `{}`.

- Build one locale per language and [choose one per read](https://arktype.io/docs/i18n#switching-locales) with `configure({ locale: () => ... })`.
- If your library types its keys, cast ArkType's (`as never`).
- Pass numbers through `locale.number`, so a rule is printed like the actual it is compared with.
- A key your catalog lacks renders whatever the library returns for it, which for i18next is the key itself, so keep the catalog complete.

## Error codes

Writers can narrow their `ctx` by its `code`, which tells them its other fields. See [Errors](https://arktype.io/docs/errors#error-codes) for every code and its fields.

# Standard Schema

> Pass a Type to any library that accepts a Standard Schema, and use other validators inside an ArkType definition.

[Standard Schema](https://standardschema.dev) is a small interface for TypeScript validators, written by the authors of ArkType, Zod and Valibot. A library that accepts a Standard Schema works with every validator that implements it, so it doesn't need an adapter for each one.

Every Type implements Standard Schema and its JSON Schema extension, [Standard JSON Schema](https://standardschema.dev/json-schema). Wherever a library asks for either, pass the Type itself. [Integrations](https://arktype.io/docs/integrations) shows the common ones.

[Precompiled](https://arktype.io/docs/precompile) validators implement Standard Schema too, and Standard JSON Schema where their build sees code read `~standard.jsonSchema` or its [`members`](https://arktype.io/docs/precompile/options#members) option sets it.

## Validation

A library validates through `T["~standard"].validate`. On success, the result's `value` is the Type's output, so morphs have already run:

```ts
const Form = type({
	name: "string",
	age: "string.integer.parse"
})

Form["~standard"].validate({ name: "Ada", age: "36" })
// { value: { name: "Ada", age: 36 } }
```

On failure, the result is `{ issues }`, one for each error in the [`ArkErrors`](https://arktype.io/docs/errors) you get from calling the Type. A library printing Standard Schema issues writes each issue's `path` before its `message`, so each issue is a copy of its error whose message is the error's [`problem`](https://arktype.io/docs/configuration#problem), which leaves the path out:

```ts
const result = Form["~standard"].validate({ name: "Ada", age: "old" })
// { issues: [{ path: ["age"], message: 'must be a well-formed integer string', ... }] }
```

A union's problem lists each branch's path from the union's, like `b must be a string or c must be a number`. A configured [`problem`](https://arktype.io/docs/configuration#problem) changes the issue's message, but a configured [`message`](https://arktype.io/docs/configuration#message) doesn't. The issues are written as `validate` returns, so unlike an `ArkErrors` read later, they describe the data as it was validated.

ArkType always validates synchronously. The spec allows a `Promise`, which is why the return type includes one.

The spec's type helpers map to a Type's input and output:

```ts
import type { StandardSchemaV1 } from "@standard-schema/spec"

const Form = type({
	name: "string",
	age: "string.integer.parse"
})

type FormInput = StandardSchemaV1.InferInput<typeof Form>
// { name: string; age: string }, same as typeof Form.inferIn

type FormOutput = StandardSchemaV1.InferOutput<typeof Form>
// { name: string; age: number }, same as typeof Form.infer
```

## Accepting any validator

If your library validates data your users describe, accept a Standard Schema instead of depending on ArkType. Your users can then bring ArkType, Zod, Valibot or any other implementation. `@standard-schema/spec` contains only types, and validators can be async, so always `await` the result:

```ts
import type { StandardSchemaV1 } from "@standard-schema/spec"

export const parse = async <schema extends StandardSchemaV1>(
	schema: schema,
	data: unknown
): Promise<StandardSchemaV1.InferOutput<schema>> => {
	const result = await schema["~standard"].validate(data)
	if (result.issues) {
		throw new Error(result.issues.map(issue => issue.message).join("\n"))
	}
	return result.value
}

const user = await parse(type({ name: "string" }), { name: "Ada" })
// { name: string }
```

## Standard JSON Schema

Libraries that need a JSON Schema, for example to describe an API or a tool for an LLM, call `T["~standard"].jsonSchema.input` or `.output`:

```ts
const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

const schema = User["~standard"].jsonSchema.input({ target: "draft-2020-12" })
```

```json
{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"type": "object",
	"properties": {
		"name": { "type": "string" },
		"age": { "type": "integer", "minimum": 0 }
	},
	"required": ["name"]
}
```

- `target` is `"draft-2020-12"`, `"draft-07"` or `"openapi-3.0"`. Any other target throws.
- `libraryOptions` is passed to [`toJsonSchema`](https://arktype.io/docs/json-schema/to-json-schema) as its options, so a caller can set a `fallback` there.
- `input` and `output` differ when the Type has morphs or defaults. For `string.integer.parse`, `input` describes a string and `output` describes an integer, and a key with a default is optional with a `default` in `input` but required in `output`.

Unlike `toJsonSchema()`, these methods don't throw when part of a Type has no JSON Schema equivalent. The library calling them can't know which fallbacks your Type needs, so each such part becomes the closest schema JSON Schema can express, or `{}` if there is none:

```ts
const Event = type({
	name: "string",
	at: "Date"
})

Event.toJsonSchema() // throws ToJsonSchemaError (code "date")

const schema = Event["~standard"].jsonSchema.input({ target: "draft-2020-12" })
// { ..., properties: { at: {}, name: { type: "string" } }, required: ["at", "name"] }
```

`{}` accepts anything, so the JSON Schema is looser than the Type. Data you validate with the Type itself is still checked in full. See [Standard JSON Schema](https://arktype.io/docs/json-schema/to-json-schema#standard-json-schema) for which parts fall back and how to write something more specific.

## Other validators in a definition

Any Standard Schema can appear in a definition, at the top level or nested. Its output is inferred and its validation runs as part of the Type:

```ts
import { type } from "arktype"
import * as v from "valibot"
import { z } from "zod"

const User = type({
	name: "string",
	age: v.number(),
	address: z.object({ street: z.string(), city: z.string() })
})

type User = typeof User.infer
// { name: string; age: number; address: { street: string; city: string } }
```

ArkType can't see inside another library's schema, so it treats one as a morph from `unknown` to that schema's output. That has consequences:

- `User.expression` shows `(In: unknown) => Out<unknown>` for it.
- `toJsonSchema()` throws on it, and `~standard.jsonSchema` writes `{}`.
- It can't be a branch of a union, because its input overlaps every other branch.
- Only synchronous validators work. ArkType doesn't await the result, so a schema that returns a `Promise`, like a Zod `refine` with an async callback, throws `Standard Schema definitions must validate synchronously (zod returned a Promise)` when validation reaches it.

# Integrations

> Use a Type directly with tRPC, oRPC, Drizzle, React Hook Form, Hono, the MCP SDK and the AI SDK.

Most libraries on this page accept a [Standard Schema](https://arktype.io/docs/standard-schema), so you pass a Type as-is with no adapter. Where a library also publishes an ArkType-specific adapter, its section shows the Standard Schema route first.

Any other library that accepts a Standard Schema works the same way. [standardschema.dev](https://standardschema.dev/schema#what-tools-frameworks-accept-speccompliant-schemas) keeps a list.

## tRPC

[tRPC](https://trpc.io/docs/server/validators) 11 accepts a Type as a procedure's input or output:

```ts
import { initTRPC } from "@trpc/server"
import { type } from "arktype"

const t = initTRPC.create()

const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

export const appRouter = t.router({
	createUser: t.procedure.input(User).mutation(({ input }) => input)
})
```

Invalid input is rejected with a `BAD_REQUEST` error before the resolver runs.

## oRPC

[oRPC](https://orpc.dev) accepts a Type the same way:

```ts
import { os } from "@orpc/server"
import { type } from "arktype"

const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})

export const createUser = os.input(User).handler(({ input }) => input)
```

To generate an OpenAPI document, give oRPC's `OpenAPIGenerator` the converter from `@orpc/arktype`:

```ts
import { experimental_ArkTypeToJsonSchemaConverter } from "@orpc/arktype"
import { OpenAPIGenerator } from "@orpc/openapi"

const generator = new OpenAPIGenerator({
	schemaConverters: [new experimental_ArkTypeToJsonSchemaConverter()]
})

const spec = await generator.generate({ createUser })
```

## Drizzle

Drizzle maintains [`drizzle-arktype`](https://orm.drizzle.team/docs/arktype), which creates Types from your tables:

```ts
import { createInsertSchema, createSelectSchema } from "drizzle-arktype"
import { integer, pgTable, serial, text } from "drizzle-orm/pg-core"

const users = pgTable("users", {
	id: serial().primaryKey(),
	name: text().notNull(),
	age: integer()
})

const User = createSelectSchema(users)
// Type<{ id: number; name: string; age: number | null }>

const NewUser = createInsertSchema(users)
// Type<{ name: string; id?: number; age?: number | null }>
```

`createUpdateSchema` is like `createInsertSchema` with every column optional. Integer columns also get their range, so `age` above must be a 32-bit integer.

## React Hook Form

[`@hookform/resolvers`](https://github.com/react-hook-form/resolvers) includes `standardSchemaResolver`:

```ts
import { standardSchemaResolver } from "@hookform/resolvers/standard-schema"
import { type } from "arktype"
import { useForm } from "react-hook-form"

const User = type({
	name: "string > 0",
	age: "number.integer >= 0"
})

export const useUserForm = () =>
	useForm({ resolver: standardSchemaResolver(User) })
```

The form's field values are typed from the Type's input, and `handleSubmit` receives its output. If you pass type arguments to `useForm` yourself, pass all three: `useForm<typeof User.inferIn, unknown, typeof User.infer>`.

The same package exports `arktypeResolver` from `@hookform/resolvers/arktype`, which behaves the same. `@hookform/resolvers` lists `arktype@^2` as an optional peer dependency, so npm refuses to install it beside a later major version of ArkType, whichever resolver you import, until you [override the peer](https://arktype.io/docs/upgrading#npm-refuses-packages-that-peer-on-arktype-2). pnpm warns, and bun installs it as is.

## Hono

[`@hono/standard-validator`](https://github.com/honojs/middleware/tree/main/packages/standard-validator) validates a request's `json`, `form`, `query`, `param`, `header` or `cookie`:

```ts
import { sValidator } from "@hono/standard-validator"
import { type } from "arktype"
import { Hono } from "hono"

const User = type({
	name: "string",
	age: "number.integer >= 0"
})

const app = new Hono()

app.post("/users", sValidator("json", User), c => {
	const user = c.req.valid("json")
	return c.json({ message: `${user.name} is ${user.age}` })
})
```

Invalid requests get a 400 response with the issues as JSON. [`@hono/arktype-validator`](https://github.com/honojs/middleware/tree/main/packages/arktype-validator) provides an equivalent `arktypeValidator`, with a required peer dependency on `arktype@^2`, so npm needs the same [override](https://arktype.io/docs/upgrading#npm-refuses-packages-that-peer-on-arktype-2) to install it.

To generate an OpenAPI document from your routes, [`hono-openapi`](https://github.com/rhinobase/hono-openapi) has a `validator` that accepts a Type, and a `resolver` for describing responses with one.

## MCP SDK

The [MCP TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/advanced/schema-libraries) accepts a Type as a tool's `inputSchema` or `outputSchema`:

```ts
import { McpServer } from "@modelcontextprotocol/server"
import { type } from "arktype"

const server = new McpServer({ name: "greeter", version: "1.0.0" })

server.registerTool(
	"greet",
	{
		description: "Greet someone by name",
		inputSchema: type({
			name: "string",
			"times?": "1 <= number.integer <= 5"
		})
	},
	async ({ name, times = 1 }) => ({
		content: [{ type: "text", text: `Hello, ${name}! `.repeat(times) }]
	})
)
```

The SDK sends clients the JSON Schema from [`~standard.jsonSchema`](https://arktype.io/docs/standard-schema#standard-json-schema) and validates arguments with the Type before your handler runs. A call with `times: 9` returns an error result, and the handler doesn't run.

This needs `@modelcontextprotocol/server`, the SDK's second major version. The first, `@modelcontextprotocol/sdk`, accepts only Zod schemas.

To serve it over stdio, connect a transport from `@modelcontextprotocol/server/stdio`:

```ts
import { McpServer } from "@modelcontextprotocol/server"
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"

const server = new McpServer({ name: "greeter", version: "1.0.0" })
// server.registerTool(...)

await server.connect(new StdioServerTransport())
```

To serve it from a route handler, like a Next.js App Router route, `createMcpHandler` builds a server for each request, and its `fetch` answers it:

```ts
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server"

const handler = createMcpHandler(() => {
	const server = new McpServer({ name: "greeter", version: "1.0.0" })
	// server.registerTool(...)
	return server
})

const serve = (request: Request) => handler.fetch(request)

export { serve as GET, serve as POST, serve as DELETE }
```

## AI SDK

The [AI SDK](https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data) accepts a Type wherever it takes a schema. For structured output:

```ts
import { generateText, Output } from "ai"
import { type } from "arktype"

const Recipe = type({
	name: "string",
	ingredients: type({ name: "string", amount: "string" }).array(),
	steps: "string[]"
})

const { output } = await generateText({
	model: "anthropic/claude-sonnet-5.5",
	output: Output.object({ schema: Recipe }),
	prompt: "Write a recipe for toast."
})
```

For a tool's input:

```ts
import { tool } from "ai"
import { type } from "arktype"

const weather = tool({
	description: "Get the weather in a city",
	inputSchema: type({ city: "string" }),
	execute: async ({ city }) => ({ city, celsius: 21 })
})
```

The model sees the JSON Schema from [`~standard.jsonSchema`](https://arktype.io/docs/standard-schema#standard-json-schema), and the AI SDK validates its response with the Type. Parts of a Type with no JSON Schema equivalent, like a `narrow`, aren't described to the model, but its response is still checked against them. Structured output arrives as JSON, so use `string.date.iso.parse` rather than `Date` for a date.

## Precompiled validators

A [precompiled](https://arktype.io/docs/precompile) validator validates through Standard Schema as a Type does, so tRPC, oRPC, Hono's validators, React Hook Form, TanStack Form and Router, Elysia, t3-env and Next.js server actions take one with nothing to set. The build bakes a JSON Schema into each validator it sees a library convert, so the MCP SDK, the AI SDK, Elysia's `@elysiajs/openapi`, hono-openapi and oRPC's `OpenAPIGenerator` with `@orpc/arktype` need nothing set either, as [`members`](https://arktype.io/docs/precompile/options#members) describes. A library that defines Types itself needs [`dependencies`](https://arktype.io/docs/precompile/options#dependencies) set:

| Library | Set in `ark.json` (or `package.json`'s `"ark"` key) |
| - | - |
| `drizzle-arktype`, which creates Types from tables as it runs | `"precompile": { "dependencies": { "drizzle-arktype": "arktype" } }` |
| t3-env's `presets-arktype`, which defines static Types | `"precompile": { "dependencies": { "@t3-oss/env-core": "aot" } }` |

Without it, a build importing `drizzle-arktype` or `presets-arktype` fails, naming the setting. A package that imports arktype itself, like `@hono/arktype-validator`, has to be bundled with your validators, so a server build with Vite fails until `ssr.noExternal` names it. [Troubleshooting](https://arktype.io/docs/precompile/troubleshooting) has each message.

A [production build](https://arktype.io/docs/precompile/options#prune) keeps `~standard` in a validator a library like Hono's `sValidator` validates with, and leaves out what nothing reads.

# fast-check

> Generate test data from a Type for property-based tests with @ark/fast-check.

`@ark/fast-check` turns a Type into a [fast-check](https://fast-check.dev) arbitrary, so your property-based tests generate data from the same definition you validate with. It works with fast-check 3 and 4.

```bash
npm install -D @ark/fast-check fast-check
```

## Generating data

`arkToArbitrary` takes a Type and returns an arbitrary:

```ts
import { arkToArbitrary } from "@ark/fast-check"
import { type } from "arktype"
import * as fc from "fast-check"

const User = type({
	name: "string > 0",
	age: "number.integer >= 0",
	"email?": "string.email",
	tags: "string[] <= 3"
})

const users = arkToArbitrary(User)

// every generated user still validates after a JSON round trip
fc.assert(
	fc.property(users, user => User.allows(JSON.parse(JSON.stringify(user))))
)
```

The arbitrary is typed `fc.Arbitrary<unknown>`. To use generated values as your Type's data, cast it:

```ts
const users = arkToArbitrary(User) as fc.Arbitrary<typeof User.inferIn>
```

Values are generated for the Type's input. For a morph like `string.trim`, you get strings that haven't been trimmed yet. Checks that run inside a morph aren't seen, so a morph that can fail rejects some of what's generated.

## What's supported

These generate only valid data:

- `string`, `number`, `bigint`, `boolean`, `symbol`, `null`, `undefined`, `unknown`, literals and unions
- number ranges, `number.integer` and divisors like `number % 3`
- string length bounds, or a single regex such as `string.email`, `string.uuid` or your own
- objects with required, optional and index signature keys
- arrays with a minimum, maximum or exact length, and tuples with optional or variadic elements
- cyclic types, like a `this` reference, a recursive scope alias or `object.json`
- `Date`, with or without bounds, and `Set`, whose elements can be any value

These throw when you call `arkToArbitrary`:

- instances of any class other than `Array`, `Date` and `Set`, including `Map`, `Function`, `Promise`, typed arrays and `type.instanceOf(MyClass)`
- regexes with a lookahead, which fast-check can't generate from. Several keywords use one, including `string.numeric`, `string.integer`, `string.date.iso` and their `.parse` variants.
- more than one regex on a string, like `string.email & string.alpha`
- a regex with a length bound, like `string.email < 50`

These are ignored, so the arbitrary generates data your Type rejects:

- `narrow` predicates, and keywords implemented as predicates rather than regexes, like `string.url`, `string.json` and `string.date`, including their `.parse` variants

When the Type accepts a reasonable share of what the arbitrary generates, filter out the rest:

```ts
import { arkToArbitrary } from "@ark/fast-check"

const Even = type("number.integer").narrow(n => n % 2 === 0)

const evens = arkToArbitrary(Even).filter(n => Even.allows(n))
```

When it doesn't, fast-check gives up after too many rejected values, and you'll need to write that arbitrary yourself.

# Ecosystem

> Community projects built on ArkType, for environment variables, Drizzle codegen and binary serialization.

These projects are maintained by their authors, not the ArkType team. For libraries that accept a Type directly, see [Integrations](https://arktype.io/docs/integrations).

## ArkEnv

[ArkEnv](https://arkenv.js.org) validates your environment variables with an ArkType definition and gives you a typed `env` object, with strings like `"3000"` already parsed into the types you declared.

It works like [T3 Env](https://env.t3.gg), built around ArkType definitions, and adds keywords for common variables like `string.host` and `number.port`.

Scaffold with `npx arkenv init` and import from `@arkenv/core` (`arkenv` on npm is the CLI).

```ts
import arkenv from "@arkenv/core"

const env = arkenv({
	HOST: "string.host",
	PORT: "number.port",
	NODE_ENV: "'development' | 'production' | 'test' = 'development'"
})

// process.env is validated and parsed when this runs
env.HOST // string
env.PORT // number
env.NODE_ENV // "development" | "production" | "test"
```

## DRZL

[DRZL](https://use-drzl.github.io/drzl) generates code from your Drizzle ORM schemas: ArkType validators, typed services and routers that reuse them.

```ts
// drzl.config.ts
import { defineConfig } from "@drzl/cli/config"

export default defineConfig({
	schema: "src/db/schemas/index.ts",
	outDir: "src/api",
	generators: [
		// 1) ArkType validators
		{ kind: "arktype", path: "src/validators/arktype", schemaSuffix: "Schema" },

		// 2) Routers (oRPC adapter), reusing ArkType schemas
		{
			kind: "orpc",
			template: "@drzl/template-orpc-service",
			includeRelations: true,
			outputHeader: { enabled: true },
			validation: {
				useShared: true,
				library: "arktype",
				importPath: "src/validators/arktype",
				schemaSuffix: "Schema"
			}
		},
		// 3) Typed services (Drizzle-aware or stub)
		{
			kind: "service",
			path: "src/services",
			dataAccess: "drizzle", // or 'stub'
			dbImportPath: "src/db/connection",
			schemaImportPath: "src/db/schemas"
		}
	]
})
```

> For more details, see the [Getting Started guide](https://use-drzl.github.io/drzl/guide/getting-started.html).

## shorn

[shorn](https://shorn.dev) turns an ArkType type into compact binary serialization. Field names and type tags stay out of the payload because the type already provides them, so there is no schema language to learn and nothing to generate.

ArkType 2.1.28 and newer implements both [Standard Schema](https://standardschema.dev/schema) and [Standard JSON Schema](https://standardschema.dev/json-schema), so a type can be passed straight to `encode`. Validation runs on encode and again on decode.

```ts
import { type } from "arktype"
import { decode, encode } from "@chichurita/shorn"

const Person = type({
	name: "string",
	age: "number.integer >= 0",
	sex: "'M' | 'F' | 'X'"
})

const bytes = encode(Person, { name: "Grace", age: 45, sex: "F" })
bytes.length // 8, where the same record is 35 bytes of minified JSON

decode(Person, bytes) // typed and validated
```

> ArkType objects are open by default, so shorn rejects undeclared properties during encoding rather than dropping data. Use `"+": "delete"` to strip expected extras. See the [ArkType guide](https://shorn.dev/validators/arktype/) for the details.

# Type API

> Every member of a Type and of the type function.

Every `Type` has the members below. Types of objects, strings, numbers, arrays and Dates add the ones under [Objects](https://arktype.io/docs/type-api#objects) and [Constraints](https://arktype.io/docs/type-api#constraints).

## Validation

A Type is a function. Call it with any data to get the validated output or [`ArkErrors`](https://arktype.io/docs/errors):

```ts
const User = type({ name: "string" })

const out = User({ name: 5 })

if (out instanceof type.errors) {
	// name must be a string
	console.error(out.summary)
} else {
	console.log(out.name)
}
```

`allows` checks only the input side of a morph, so a value can be allowed and still fail when the Type is called. See [Validation](https://arktype.io/docs/validation) for more.

### `assert`

validate and return transformed data or throw

- sugar to avoid checking for [type.errors](https://arktype.io/docs/errors) if they are unrecoverable
- warning: throws `TraversalError`

```ts
const CriticalPayload = type({
    superImportantValue: "string"
})
// throws TraversalError: superImportantValue must be a string (was missing)
const data = CriticalPayload.assert({ irrelevantValue: "whoops" })
console.log(data.superImportantValue) // valid output can be accessed directly
```

### `allows`

check input without applying morphs

- good for stuff like filtering that doesn't benefit from detailed errors

```ts
const Numeric = type("number | bigint")
// [0, 2n]
const numerics = [0, "one", 2n].filter(Numeric.allows)
```

### `from`

alias for [`assert`](https://arktype.io/docs/type-api#assert) with typed input

```ts
const T = type({ foo: "string" });
// TypeScript: Type 'number' is not assignable to type 'string'
const data = T.from({ foo: 5 });
```

## Inference

### `infer`

type of output this returns

- inference-only property that will be `undefined` at runtime

```ts
const parseNumber = type("string").pipe(s => Number.parseInt(s))
type ParsedNumber = typeof parseNumber.infer // number
```

### `inferIn`

type of input this allows

- inference-only property that will be `undefined` at runtime

```ts
const parseNumber = type("string").pipe(s => Number.parseInt(s))
type UnparsedNumber = typeof parseNumber.inferIn // string
```

### `inferOut`

type of output this returns

- alias of [`infer`](https://arktype.io/docs/type-api#infer)
- inference-only property that will be `undefined` at runtime

```ts
const parseNumber = type("string").pipe(s => Number.parseInt(s))
type ParsedNumber = typeof parseNumber.inferOut // number
```

### `inferIntrospectableOut`

type of output that can be introspected at runtime (e.g. via [`out`](https://arktype.io/docs/type-api#out))

- warning: If your Type contains morphs, they will be inferred as `unknown` unless they are an ArkType keyword or have an explicitly defined output validator.
- inference-only property that will be `undefined` at runtime

```ts
const Unmorphed = type("string")
// with no morphs, we can introspect the input and output as a single Type
type UnmorphedOut = typeof Unmorphed.inferIntrospectableOut // string

const Morphed = type("string").pipe(s => s.length)
// with a standard user-defined morph, TypeScript can infer a
// return type from your function, but we have no way to
// know the shape at runtime
type MorphOut = typeof Morphed.inferIntrospectableOut  // unknown

const Validated = type("string").pipe(s => s.length).to("number")
// morphs with validated output, including all morph keywords, are introspectable
type ValidatedMorphOut = typeof Validated.inferIntrospectableOut
```

### `t`

generic parameter representing this Type

- inference-only property that will be `undefined` at runtime
- warning: May contain types representing morphs or default values that would be inaccurate if used directly for runtime values. In those cases, you should use [`infer`](https://arktype.io/docs/type-api#infer) or [`inferIn`](https://arktype.io/docs/type-api#inferin) on this object instead.

### `as`

cast the way this is inferred

- inference-only function that does nothing at runtime

```ts
// Type<`LEEEEEEEE${string}ROY`>
const Leeroy = type(/^LE{8,}ROY$/).as<`LEEEEEEEE${string}ROY`>()
```

### `brand`

add a compile-time brand to output

- inference-only function that does nothing at runtime

```ts
const Palindrome = type("string")
    .narrow(s => s === [...s].reverse().join(""))
    .brand("palindrome")
// Brand<string, "palindrome">
const out = Palindrome.assert("racecar")
```

## Metadata

### `description`

human-readable English description

- works best for primitive values

```ts
const N = type("0 < number <= 100")
console.log(N.description) // positive and at most 100
```

### `expression`

syntax string similar to native TypeScript

- works well for both primitives and structures

```ts
const Loc = type({ coords: ["number", "number"] })
console.log(Loc.expression) // { coords: [number, number] }
```

### `meta`

metadata like custom descriptions and error messages

- type [can be customized](https://arktype.io/docs/configuration#custom) for your project

### `configure`

add metadata to shallow references

- warning: does not affect error messages within properties of an object

```ts
const NotOdd = type("number % 2").configure({ description: "not odd" })
// all constraints at the root are affected
const odd = NotOdd(3) // must be not odd
const nonNumber = NotOdd("two") // must be not odd

const NotOddBox = type({
   // we should have referenced notOdd or added meta here
   notOdd: "number % 2",
// but instead chained from the root object
}).configure({ description: "not odd" })
// error message at path notOdd is not affected
const oddProp = NotOddBox({ notOdd: 3 }) // notOdd must be even
// error message at root is affected, leading to a misleading description
const nonObject = NotOddBox(null) // must be not odd
```

### `describe`

add description to shallow references

- equivalent to `.configure({ description })` (see [`configure`](https://arktype.io/docs/type-api#configure))
- warning: does not affect error messages within properties of an object

```ts
const AToZ = type(/^a.*z$/).describe("a string like 'a...z'")
const good = AToZ("alcatraz") // "alcatraz"
// ArkErrors: must be a string like 'a...z'
const badPattern = AToZ("albatross")
```

## Composition

### `and`

intersect the parsed Type, throwing if the result is unsatisfiable

```ts
// Type<{ foo: number; bar: string }>
const T = type({ foo: "number" }).and({ bar: "string" })
// ParseError: Intersection at foo of number and string results in an unsatisfiable type
const Bad = type({ foo: "number" }).and({ foo: "string" })
```

### `or`

union with the parsed Type

- warning: a union that could apply different morphs to the same data is a ParseError ([docs](https://arktype.io/docs/expressions#union-morphs))

```ts
// Type<string | { box: string }>
const T = type("string").or({ box: "string" })
```

### `intersect`

intersect the parsed Type, returning an introspectable `Disjoint` if the result is unsatisfiable

```ts
import { Type } from "arktype"

// Type<{ foo: number; bar: string }> | Disjoint
const T = type({ foo: "number" }).intersect({ bar: "string" })
const Bad = type("number > 10").intersect("number < 5")
// logs "Intersection of > 10 and < 5 results in an unsatisfiable type"
if (!(Bad instanceof Type)) console.log(Bad.summary)
```

### `array`

an array of this

```ts
// Type<{ rebmun: number }[]>
const T = type({ rebmun: "number" }).array();
```

### `optional`

[optional definition](https://arktype.io/docs/objects#properties-optional)

- warning: unlike most other methods, this creates a definition rather than a Type

```ts
const Prop = type({ foo: "number" })
// Type<{ bar?: { foo: number } }>
const Obj = type({ bar: Prop.optional() })
```

### `default`

[defaultable definition](https://arktype.io/docs/objects#properties-defaultable)

- object defaults can be returned from a function
- warning: throws if the default value is not allowed
- warning: unlike most other methods, this creates a definition rather than a Type

```ts
// Type<{ count: Default<number, 0> }>
const State = type({ count: type.number.default(0) })
const Prop = type({ nested: "boolean" })
const ForObj = type({
    key: Prop.default(() => ({ nested: false }))
})
```

## Narrows and morphs

### `narrow`

apply a predicate function to output

- go-to fallback for validation not composable via built-in types and operators
- runs after all other validators and morphs, if present
- [Type predicates](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) can be used as casts

```ts
const Palindrome = type("string").narrow(s => s === [...s].reverse().join(""))

const ThisYear = type("string.date.parse").narrow((date, ctx) =>
		date.getFullYear() === new Date().getFullYear() || ctx.mustBe("the current year")
)
// Type<`${string}.tsx`>
const WithPredicate = type("string").narrow((s): s is `${string}.tsx` => s.endsWith(".tsx"))
```

### `filter`

apply a predicate function to input

- warning: the behavior of [`narrow`](https://arktype.io/docs/type-api#narrow), this method's output counterpart, is usually more desirable
- most useful for morphs with input types that are re-used externally
- [Type predicates](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) can be used as casts

```ts
const stringifyUser = type({ name: "string" }).pipe(user => JSON.stringify(user))
const stringifySafe = stringifyUser.filter(user => user.name !== "Bobby Tables")
// Type<(In: `${string}Z`) => To<Date>>
const WithPredicate = type("string.date.parse").filter((s): s is `${string}Z` =>
    s.endsWith("Z")
)
```

### `pipe`

pipe output through arbitrary transformations or other Types

```ts
const User = type({ name: "string" })

// parse a string and validate the result as a User
const parseUser = type("string").pipe(s => JSON.parse(s), User)
```

### `to`

parse a definition as an output validator

- `to({ name: "string" })` is equivalent to `.pipe(type({ name: "string" }))`

```ts
// parse a string and validate the result as a user
const parseUser = type("string").pipe(s => JSON.parse(s)).to({ name: "string" })
```

### `in`

deeply extract inputs

- will never include morphs
- good for generating JSON Schema or other non-transforming formats

```ts
const User = type({
   age: "string.numeric.parse"
})
// { age: 25 } (age parsed to a number)
const out = User({ age: "25" })
// { age: "25" } (age is still a string)
const inOut = User.in({ age: "25" })
```

### `out`

deeply extract outputs

- will never include morphs
- warning: if your type includes morphs, their output will likely be unknown unless they were defined with an explicit output validator via `.to(outputDef)` or `.pipe(morph, outputType)`

```ts
const join = type("string[]").pipe(a => a.join(","))

const T = type({
   // all keywords have introspectable output
   keyword: "string.numeric.parse",
   // TypeScript knows this returns a string, but we can't introspect that at runtime
   unvalidated: join,
   // if needed, it can be made introspectable with an output validator
   validated: join.to("string")
})

// Type<{ keyword: number; unvalidated: unknown; validated: string }>
const Out = T.out
```

### `encode`

deeply invert morphs to encode output as input

- warning: requires `import "arktype/codecs"`, and throws if a morph has no inverse

```ts
const EpochMs = codec("number.integer", "Date", {
    decode: n => new Date(n),
    encode: d => d.getTime()
})
const Event = type({ name: "string", at: EpochMs })
// { name: "launch", at: 0 }
const encoded = Event.encode({ name: "launch", at: new Date(0) })
```

### pipe.try

Like `pipe`, but a morph that throws adds an error instead of throwing:

```ts
const ParseJson = type("string").pipe.try(s => JSON.parse(s))

ParseJson('{"a": 1}') // { a: 1 }
// ArkErrors: must be valid according to an anonymous predicate (SyntaxError: ...)
ParseJson("{")
```

## Comparison

### `equals`

check if the parsed Type's constraints are identical

- equal types have identical input and output constraints and transforms
- ignores associated [`meta`](https://arktype.io/docs/type-api#meta), which does not affect the set of allowed values

```ts
const DivisibleBy6 = type.number.divisibleBy(6).moreThan(0)
// false (left side must also be positive)
DivisibleBy6.equals("number % 6")
// false (right side has an additional <100 constraint)
console.log(DivisibleBy6.equals("0 < (number % 6) < 100"))
const ThirdTry = type("(number % 2) > 0").divisibleBy(3)
// true (types are normalized and reduced)
console.log(DivisibleBy6.equals(ThirdTry))
```

### `ifEquals`

narrow this based on an [`equals`](https://arktype.io/docs/type-api#equals) check

- ignores associated [`meta`](https://arktype.io/docs/type-api#meta), which does not affect the set of allowed values

```ts
const N = type.raw(`${Math.random()}`)
// Type<0.5> | undefined
const Ez = N.ifEquals("0.5")
```

### `extends`

check if this is a subtype of the parsed Type

- a subtype must include all constraints from the base type
- unlike [`equals`](https://arktype.io/docs/type-api#equals), additional constraints may be present
- ignores associated [`meta`](https://arktype.io/docs/type-api#meta), which does not affect the set of allowed values

```ts
type.string.extends("unknown") // true
type.string.extends(/^a.*z$/) // false
```

### `ifExtends`

narrow this based on an [`extends`](https://arktype.io/docs/type-api#extends) check

- ignores associated [`meta`](https://arktype.io/docs/type-api#meta), which does not affect the set of allowed values

```ts
const N = type(Math.random() > 0.5 ? "true" : "0") // Type<0 | true>
const Ez = N.ifExtends("boolean") // Type<boolean> | undefined
```

### `overlaps`

check if a value could satisfy this and the parsed Type

- warning: will return true unless a `Disjoint` can be proven

```ts
type.string.overlaps("string | number") // true (e.g. "foo")
type("string | number").overlaps("1") // true (1)
type("number > 0").overlaps("number < 0") // false (no values exist)

const NoAt = type("string").narrow(s => !s.includes("@"))
NoAt.overlaps("string.email") // true (no values exist, but not provable)
```

### `extract`

extract branches `extend`ing the parsed Type

```ts
// Type<true | 0 | 2>
const T = type("boolean | 0 | 'one' | 2 | bigint").extract("number | 0n | true")
```

### `exclude`

exclude branches `extend`ing the parsed Type

```ts
// Type<false | 'one' | bigint>
const T = type("boolean | 0 | 'one' | 2 | bigint").exclude("number | 0n | true")
```

### distribute

Map each branch of a union, and optionally reduce the results. A Type that isn't a union is a single branch. This method is experimental.

```ts
const T = type("string | number | bigint")

T.distribute(branch => branch.expression) // ["bigint", "number", "string"]

T.distribute(
	branch => branch.expression,
	expressions => expressions.join(" or ")
) // "bigint or number or string"
```

## Objects

These are available on a Type whose output is an object. See [Objects](https://arktype.io/docs/objects#properties-structural) for how each one handles arrays, index signatures and defaults.

### `get`

Get the `Type` of a property of this `Type<object>`.

```ts
type({ foo: "string" }).get("foo") // Type<string>
```

### `pick`

Create a copy of this `Type` with only the specified properties.

- warning: returns a new object built from the properties it extracts, so a root narrow, filter or metadata on this `Type` is not carried over ([docs](https://arktype.io/docs/objects#properties-structural))

```ts
type({ foo: "string", bar: "number" }).pick("foo") // Type<{ foo: string }>
```

### `omit`

Create a copy of this `Type` with all properties except the specified ones.

- warning: returns a new object built from the properties it extracts, so a root narrow, filter or metadata on this `Type` is not carried over ([docs](https://arktype.io/docs/objects#properties-structural))

```ts
type({ foo: "string", bar: "number" }).omit("foo") // Type<{ bar: number }>
```

### `merge`

Merge another `Type` definition, overriding properties of this `Type` with the duplicate keys.

- warning: returns a new object built from the properties it extracts, so a root narrow, filter or metadata on this `Type` is not carried over ([docs](https://arktype.io/docs/objects#properties-structural))

```ts
type({ a: "1", b: "2" }).merge({ b: "3", c: "4" }) // Type<{ a: 1; b: 3; c: 4 }>
```

### `required`

Create a copy of this `Type` with all properties required.

- warning: returns a new object built from the properties it extracts, so a root narrow, filter or metadata on this `Type` is not carried over ([docs](https://arktype.io/docs/objects#properties-structural))
- like TS's `Required`, an array or tuple base is preserved and applied to its elements, e.g. `type(["string", "number"]).required()`

```ts
const T = type({ "foo?": "string" }).required() // Type<{ foo: string }>
```

### `partial`

Create a copy of this `Type` with all properties optional.

- warning: returns a new object built from the properties it extracts, so a root narrow, filter or metadata on this `Type` is not carried over ([docs](https://arktype.io/docs/objects#properties-structural))
- like TS's `Partial`, an array or tuple base is preserved and applied to its elements, e.g. `type(["string", "number"]).partial()`

```ts
const T = type({ foo: "string" }).partial() // Type<{ foo?: string }>
```

### `map`

Create a copy of this `Type` with each of its properties transformed by the provided function. Return `[]` to remove a property.

- warning: returns a new object built from the properties it extracts, so a root narrow, filter or metadata on this `Type` is not carried over ([docs](https://arktype.io/docs/objects#properties-structural))

```ts
type({ foo: "string" }).map(prop => ({ key: prop.key, value: prop.value.or("null") })) // Type<{ foo: string | null }>
```

### `props`

List of property info of this `Type<object>`.

```ts
type({ foo: "string = 'x'" }).props // [{ kind: "optional", key: "foo", value: Type<string>, default: "x" }]
```

### `onUndeclaredKey`

apply undeclared key behavior

- `"ignore"` (default) - allow and preserve extra properties
- `"reject"` - disallow extra string keys
- `"delete"` - output only declared keys

### `onDeepUndeclaredKey`

deeply apply undeclared key behavior

- `"ignore"` (default) - allow and preserve extra properties
- `"reject"` - disallow extra string keys
- `"delete"` - output only declared keys

### readonly

Mark every property `readonly` in the inferred type. Validation is unchanged.

```ts
// Type<{ readonly id: number }>
const Frozen = type({ id: "number" }).readonly()
```

### keyof

A Type of this object's keys.

```ts
// Type<"id" | "name">
const Key = type({ id: "number", name: "string" }).keyof()
```

## Constraints

Each method adds a constraint you could also write in a [string definition](https://arktype.io/docs/intro/adding-constraints), and returns a Type of the same kind. A Date bound can be a `Date`, a number of milliseconds or a string `new Date()` accepts.

| Method | Available on | Constraint |
| - | - | - |
| `matching` | string | matches a [regex](https://arktype.io/docs/primitives#string-patterns) |
| `atLeastLength` | string, array | length `>= n` |
| `atMostLength` | string, array | length `<= n` |
| `moreThanLength` | string, array | length `> n` |
| `lessThanLength` | string, array | length `< n` |
| `exactlyLength` | string, array | length `== n` |
| `atLeast` | number | `>= n` |
| `atMost` | number | `<= n` |
| `moreThan` | number | `> n` |
| `lessThan` | number | `< n` |
| `divisibleBy` | number | `% n` |
| `atOrAfter` | Date | `>= date` |
| `atOrBefore` | Date | `<= date` |
| `laterThan` | Date | `> date` |
| `earlierThan` | Date | `< date` |

```ts
const Username = type.string.matching("^[a-z]+$").atMostLength(16)

// ArkErrors: must be matched by ^[a-z]+$
Username("ArkType")

// Type<`a${string}z`>, inferred from the pattern
const AToZ = type.string.matching("^a.*z$")

const Even = type.number.divisibleBy(2)

// ArkErrors: must be even
Even(3)
```

## Serialization

[To JSON Schema](https://arktype.io/docs/json-schema/to-json-schema) covers `toJsonSchema()` and `~standard.jsonSchema`: their options, what they can't represent, and the fallbacks. [Standard Schema](https://arktype.io/docs/standard-schema) covers `~standard.validate`.

### `json`

internal JSON representation

### `toJSON`

alias of [`json`](https://arktype.io/docs/type-api#json) for `JSON.stringify` compatibility

### `toJsonSchema`

generate a JSON Schema

- warning: throws `ToJsonSchema.Error` if this cannot be converted to JSON Schema

### `~standard`

The Type's [StandardSchema](https://github.com/standard-schema/standard-schema) properties

## Introspection

### `$`

[Scope](https://arktype.io/docs/scopes) in which chained methods are parsed

### `precompilation`

precompiled JS used to optimize validation

- warning: will be `undefined` in [jitless](https://arktype.io/docs/configuration#jitless) mode

### `select`

query internal node references

experimental: filters and returns the Type's internal representation from `@ark/schema`

```ts
// ["blue", "red"]
const values = type("'red' | 'blue'").select("unit").map(u => u.unit)
```

### internal

The node from `@ark/schema` that a Type is built from. Its API is not semver-stable. See [Nodes](https://arktype.io/docs/internals/nodes).

```ts
type("string").internal.kind // "domain"
```

## Members of type

The `type` function has members of its own. Each returns a `Type` unless noted.

| Member | What it does |
| - | - |
| `type.unit` | a Type of exactly one value |
| `type.enumerated` | a Type of any of the values passed |
| `type.valueOf` | a Type of an object's values, e.g. a TypeScript `enum` |
| `type.instanceOf` | a Type of instances of a class |
| `type.or` | a union of every definition passed |
| `type.and` | an intersection of every definition passed |
| `type.merge` | object definitions merged, later keys winning |
| `type.pipe` | a pipe through each morph or Type passed |
| `type.fn` | a [validated function](https://arktype.io/docs/expressions#fn) |
| `type.match` | a [matcher](https://arktype.io/docs/match) |
| `type.generic` | a [generic](https://arktype.io/docs/generics) |
| `type.declare` | a Type checked against a TypeScript type you [declare](https://arktype.io/docs/declare) |
| `type.define` | your definition, unchanged, type-checked as `type` would check it |
| `type.raw` | `type` without type-level parsing, for dynamic definitions |
| `type.schema` | a Type from an `@ark/schema` [schema](https://arktype.io/docs/internals/schemas) |
| `type.scope` | a [scope](https://arktype.io/docs/scopes), the same as `scope` |
| `type.module` | a [module](https://arktype.io/docs/scopes#modules), the scope's exported aliases |
| `type.keywords` | every [keyword](https://arktype.io/docs/keywords), e.g. `type.keywords.string.email` |
| `type.errors` | the `ArkErrors` class, for `out instanceof type.errors` |
| `type.hkt` | the `Hkt` class for [higher-kinded generics](https://arktype.io/docs/generics#hkt) |
| `type.$` | the scope `type` parses definitions in |
| `type.string`, ... | root keywords like `string`, `Date` and `Record` as Types or generics |

```ts
// Type<"foo">
const Foo = type.unit("foo")

// Type<"a" | 1 | null>
const Some = type.enumerated("a", 1, null)

// Type<string | number>
const StringOrNumber = type.or("string", "number")

// Type<{ a: 3; b: 2; c: 4 }>
const Merged = type.merge({ a: "1", b: "2" }, { a: "3", c: "4" })

// Type<Map<unknown, unknown>>
const AnyMap = type.instanceOf(Map)

// Type<any>, since the definition is only parsed at runtime
const Dynamic = type.raw("number")

// { name: "string" }, checked like a definition passed to type
const userDef = type.define({ name: "string" })
```

`type.valueOf` skips the reverse mappings TypeScript adds to a numeric `enum`:

```ts
enum Color {
	Red,
	Green = "green"
}

// Type<Color>, allowing 0 and "green" but not "Red"
const AnyColor = type.valueOf(Color)
```

# Packages

> Every package ArkType publishes, its entrypoints, and what to import from each.

To define and validate Types, install `arktype`. It brings `arkregex`, `@ark/schema`, `arksets` and `@ark/util` with it, so you never install those yourself to use ArkType. Each package publishes under exactly one name, the one listed here; `@ark/type`, `@ark/regex` and the `@arktype/*` names are [no longer published](https://arktype.io/docs/upgrading#package-names).

| Package | Install it to | Docs |
| - | - | - |
| `arktype` | define Types and validate data | [Setup](https://arktype.io/docs/intro/setup) |
| `@ark/aot` | construct your Types when you build | [Precompile](https://arktype.io/docs/precompile) |
| `arkregex` | write regular expressions with inferred types | [ArkRegex](https://arktype.io/docs/regex) |
| `@ark/attest` | assert types and benchmark them in your tests | [Attest](https://arktype.io/docs/attest) |
| `@ark/json-schema` | build a Type from a JSON Schema | [From JSON Schema](https://arktype.io/docs/json-schema/from-json-schema) |
| `@ark/fast-check` | generate test data from a Type with fast-check | [fast-check](https://arktype.io/docs/fast-check) |
| `@ark/schema` | build Types from nodes instead of syntax (not semver-stable) | [Internals](https://arktype.io/docs/internals) |
| `arksets` | relate, combine and convert schemas from any format | [ArkSets](https://arktype.io/docs/sets) |
| `@ark/util` | nothing: it's shared by the other packages | |
| `@ark/fs` | nothing: it's the filesystem layer `@ark/attest` uses | |

The VS Code extensions, "ArkType" and "ArkThemes", are on the [Editor](https://arktype.io/docs/editor) page.

## arktype

| Entrypoint | Import it for |
| - | - |
| `arktype` | everything you use day to day (below) |
| `arktype/codecs` | `codec`, and the `.encode` every Type has once it's imported ([Codecs](https://arktype.io/docs/codecs)) |
| `arktype/errors` | installs `errors: "first"` and `"none"` ([errors](https://arktype.io/docs/configuration#errors)) |
| `arktype/mutatesInput` | installs `mutatesInput: true` and `"always"` ([mutatesInput](https://arktype.io/docs/configuration#mutatesinput)) |
| `arktype/runtime` | what [precompiled](https://arktype.io/docs/precompile) validators run on. A build resolves `arktype` to it; you don't import it yourself |
| `arktype/config` | `configure`, before anything else from `arktype` is imported |
| `arktype/locales/en`, `arktype/locales/de` | the `en` and `de` [locales](https://arktype.io/docs/i18n) |
| `arktype/i18n` | helpers for [writing a locale](https://arktype.io/docs/i18n#writing-a-locale): `listPattern`, `isolate`, `labelOf`, `groupByPath`, `describeCause`, `describeMissing`, `writeKeywordExpected` |
| `arktype/internal`, `arktype/internal/*.ts` | every module's exports, for tools built on ArkType. Not semver-stable. |

`arktype` exports:

- `type`, `scope`, `match`, `generic`, `declare`, `define` and `fn` to define Types, and `keywords` and `ark`, the keywords as a module and as a scope.
- `regex`, the same function `arkregex` exports.
- `Type`, `Module` and `Generic` to check a value with `instanceof`, and `Hkt` to write a [higher-kinded generic](https://arktype.io/docs/generics#hkt).
- `ArkErrors`, `ArkError`, `TraversalError` and `ParseError`, the [errors](https://arktype.io/docs/errors) ArkType returns and throws, and `Traversal`, the type of the `ctx` a [narrow or morph](https://arktype.io/docs/traversal-api) receives.
- `annotatingFallback`, a [JSON Schema fallback](https://arktype.io/docs/json-schema/to-json-schema#annotatingfallback), and `inferred`, the symbol key a Type's inferred type is declared under.
- types such as `Out`, `Brand`, `Json`, `JsonSchema`, `ArkErrorCode`, `Locale`, `Scope`, `BaseType` and `inferDefinition`/`validateDefinition` for [wrapping `type`](https://arktype.io/docs/generics#external).

`arktype` exports `configure` too, but importing it from there loads all of `arktype` first. Configure in a file of its own, and import that file before anything else:

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

configure({ onUndeclaredKey: "delete" })
```

```ts
import "./config.ts"
import { type } from "arktype"
```

## Other packages

- **`@ark/aot`** has an entrypoint for each way to run it: `@ark/aot/unplugin` (`precompile.vite()`, `.rollup()`, `.webpack()` and the other bundlers), `@ark/aot/node` (`register()`), `@ark/aot/bun` (`precompile()`), `@ark/aot/turbopack` (a loader, `withPrecompile()` for `next.config` and `@ark/aot/turbopack/runtime` for its alias) and `@ark/aot/eslint` (`configs.recommended`). It installs an `arktype-precompile` CLI for `--check` and `--declare`, and `@ark/aot` itself exports `Precompiler`, whose `analyze()` the CLI and ESLint rule run. It needs Node 22.12 or later, and `typescript` 5.5 to 6 for declarations. See [Setup](https://arktype.io/docs/precompile/setup).
- **`arkregex`** exports `regex`, which is also exported from `arktype`, and the `Regex` type.
- **`@ark/attest`** exports `attest`, `bench`, `setup` and `teardown`, and installs an `attest` CLI. Install it as a dev dependency.
- **`@ark/json-schema`** exports `jsonSchemaToType` and `JsonSchemaScope`.
- **`@ark/fast-check`** exports `arkToArbitrary`. It needs `fast-check` 3 or 4 installed beside it.
- **`@ark/schema`** exports nodes, `rootSchema`, `schemaScope` and the classes behind `ArkErrors`, with `config`, `i18n`, `codecs`, `errors`, `mutatesInput` and `runtime` entrypoints like `arktype`'s.
- **`arksets`** exports `parse`, `isSubset`, `isEqual`, `isDisjoint`, `intersect`, `union`, `discriminate` and `toJsonSchema`, and installs set algebra into `@ark/schema` when imported. `arktype` imports only that engine, from `arksets/internal`.

`@ark/json-schema`, `@ark/fast-check` and `@ark/attest` each depend on an exact version of `arktype`, and `@ark/aot` precompiles with the `arktype` it imports. Install the versions released alongside your `arktype` so your project doesn't load two copies of it.

`arkregex`, `@ark/schema`, `arksets` and `@ark/util` have an `./internal` entrypoint like `arktype`'s, and every package above has `./internal/*.ts` deep imports. None of them are semver-stable.

# FAQ

> Answers to common questions about ArkType's behavior, configuration and TypeScript integration.

## Why do I see type errors in an ArkType package in `node_modules`?

This can occur due to incompatibilities between your `tsconfig.json` and ours. It is harmless as long as your types are correct in source.

We recommend enabling [`skipLibCheck`](https://www.typescriptlang.org/tsconfig/#skipLibCheck) in every TypeScript project to avoid false positives like this and improve editor performance.

## Why does `number` reject `Infinity`?

`number` excludes `NaN`, `Infinity` and `-Infinity` by default, so validated numbers are finite. JSON can't represent them either: `JSON.stringify(Infinity)` is `"null"`. To allow them in one type, add the corresponding keyword:

```ts
const Bound = type("number | number.Infinity | number.NegativeInfinity")
```

To allow them everywhere, configure `numberAllowsInfinity` or `numberAllowsNaN` (see [Configuration](https://arktype.io/docs/configuration)).

## Why can't I index `ArkErrors` like an array?

`ArkErrors` isn't an `Array`. Its errors are in `issues`, one per path:

```ts
const out = type({ name: "string" })({})

if (out instanceof type.errors) {
	// ArkError: name must be a string (was missing)
	out.issues[0]
	out.issues.map(e => e.message)
	for (const error of out.issues) console.log(error.path)
}
```

See [Errors](https://arktype.io/docs/errors) for everything an error carries.

## Why isn't my configuration applied?

Global config is fixed when the first Type is created, by a definition or by reading a keyword like `type.number`. Calling `configure` after that throws a `ParseError`: `configure() must be called before any Type is created, so import the module calling it before any module that creates one`. Put it in its own file. See [Configuration](https://arktype.io/docs/configuration).

## Does a morph change my input?

Only if you mutate it, or configure [`mutatesInput`](https://arktype.io/docs/configuration#mutatesinput). A morph receives the validated value itself, not a copy, so mutating its argument mutates the caller's data. Return a new value instead:

```ts
const addTag = type({ tags: "string[]" }).pipe(o => ({
	...o,
	tags: [...o.tags, "new"]
}))
```

## Should I precompile?

If your app is bundled, yes. A [precompiled](https://arktype.io/docs/precompile) build ships each Type as a standalone validator, without arktype's parser and without generating code at runtime, and your definitions don't change. Stay dynamic where there's no build step or a program composes Types at runtime. See [Dynamic vs Precompiled](https://arktype.io/docs/precompile/dynamic-vs-precompiled).

## Can I get error messages in another language?

Yes. ArkType ships English and German, and you can write a locale for any other language. See [i18n](https://arktype.io/docs/i18n).

## How does ArkType compare to Zod or Valibot?

All three validate at runtime and infer TypeScript types. The main difference is how you write a definition: ArkType uses TypeScript's own syntax, while Zod and Valibot use function calls.

```ts
// z.object({ name: z.string(), age: z.number().int().min(0).optional() })
const User = type({
	name: "string",
	"age?": "number.integer >= 0"
})
```

That means dynamic ArkType parses your definitions at runtime, so it ships a parser, and its bundle is larger than Zod's or Valibot's. [Precompiled](https://arktype.io/docs/precompile), it ships no parser. On Valibot's own login form, ArkType's default build reports an error for every invalid field, with the form's messages, in a smaller bundle than Valibot: 1.01 kB gzipped against 1.55 kB.

Coming from Zod, most APIs have a direct equivalent:

| Zod | ArkType |
| - | - |
| `z.object({ ... })` | `type({ ... })` |
| `.optional()` on a property | `"key?": ...` |
| `.default(value)` | `"number = 0"` as a property value |
| `z.enum(["a", "b"])` | `"'a' \| 'b'"` |
| `z.array(T)` | `T.array()` or `"string[]"` |
| `z.infer<typeof T>` | `typeof T.infer` |
| `T.parse(data)` | `T.assert(data)` |
| `T.safeParse(data)` | `T(data)`, then `instanceof type.errors` |
| `.refine(fn)` | `.narrow(fn)` |
| `.transform(fn)` | `.pipe(fn)` |

All three implement [Standard Schema](https://arktype.io/docs/standard-schema), so a library that accepts one of them accepts the others.

## Why isn't my wrapper generic working?

TypeScript's generic inference has many edge cases. General patterns for wrapping Types and definitions are outlined [in the Generics docs](https://arktype.io/docs/generics#external).

> **Type-level logic needs a cast**
>
> When implementing a function with a generic return type, you will almost always need to cast in your implementation, either explicitly via `as` or by using an overload.
>
> Think of it as trading internal safety for external precision. As long as the function you're writing will be called many times externally, the overhead is justified. If not, it may not need to be generic at all. A broad return type like `string` as opposed to `${prefix}.${key}` may be sufficient.
>
> **See an example**
>
> ```ts
> // via explicit cast
> const createBox = <const def>(
> 	of: type.validate<def>
> ): type.instantiate<{ box: def }> =>
> 	type.raw({
> 		box: of
> 		// when implementing generics, never is your go-to
> 		// for allowing an arbitrary assignment with less risk than `any`
> 	}) as never
>
> // via overloads
> // only the external signatures are considered on invocation
> function createBox2<const def>(
> 	of: type.validate<def>
> ): type.instantiate<{ box: def }>
> // the signature associated with the implementation is much looser and should
> // be thought of as equivalent to casting in terms of type safety
> function createBox2(of: unknown) {
> 	return type.raw({
> 		box: of
> 	})
> }
>
> // Type<{ box: string }>
> const Box = createBox("string")
> ```
>
> In both cases, we've explicitly annotated the return type we want and used some method of casting internally to allow our implementation. This is a common pattern for implementing generic functions and, more generally, associating an implementation with typings TS can't infer on its own.

For anything more complex, you'll have to rely on your understanding of type manipulation. Tracing your way through ArkType's internal types may uncover helpful patterns, and you may find friendly folks [in our Discord](https://arktype.io/discord) willing to lend a hand.

We can't guarantee your generics will behave the way you expect, since that depends on how TypeScript infers them in your code rather than on ArkType's API.

## What's up with your type/Type casing?

You might have noticed in our documentation we use PascalCase for some Types and camelCase for others:

```ts
const User = type({
	name: "string",
	platform: "'android' | 'ios'",
	"version?": "number | string"
})

const parseJson = type("string.json.parse").to({
	name: "string",
	version: "string.semver"
})
```

Types that only validate are named like TypeScript types. Types that transform their input behave like functions, so they're named like functions.

This distinction evolved from the rules we use for casing our internal TypeScript types:

- Use `PascalCase` for...
  - Entities/non-generic types (e.g. `User`, `SomeData`)
  - Generic types with noun names, like `Array<t>`. As a rule of thumb, your generic should be named this way if all its parameters have defaults (unfortunately TS's built-in `Array` type doesn't have a default parameter, but it probably should have been `unknown`!)

- Use `camelCase` for...
  - Generic types with verb names like `inferDomain<t>`. Types named this way should generally have at least one required parameter.
  - Parameter names, e.g. `t` in `Array<t>`

If you don't like this, feel free to use whatever casing rules best suit your repo. It doesn't affect your Types or scope aliases.

## Is there a way to create an async morph?

Other than handling it as a promise on the output object, no.

As it stands, it doesn't seem worth the significant complexity it would add to morphs in the type system.

If you have a compelling use case, let us know on [this GitHub issue](https://github.com/arktypeio/arktype/issues/462).

---

--- METRICS ---
- Files Extracted: 31
- Estimated Token Budget: ~135654 tokens
- Canonical Reference: https://codewiki.google/github.com/arktypeio/arktype
