arktype 3.0.0-beta.0 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +162 -10
  2. package/out/attributes.d.ts +4 -2
  3. package/out/checkers.d.ts +37 -2
  4. package/out/{chunk-Z4F45ZTE.js → chunk-2U2AWCI3.js} +3 -3
  5. package/out/{chunk-5NJWD7CO.js → chunk-5U2ZMDNI.js} +215 -140
  6. package/out/{chunk-KJ3C5GTL.js → chunk-DLWCO4RV.js} +1 -1
  7. package/out/{chunk-H4VRNKMB.js → chunk-E3DZXEZK.js} +1 -1
  8. package/out/{chunk-EJZJUYPI.js → chunk-EVCML554.js} +2 -2
  9. package/out/{chunk-KI2MOYNT.js → chunk-GPNK5353.js} +184 -32
  10. package/out/{chunk-LUXERINN.js → chunk-RAZ3TXOE.js} +40 -38
  11. package/out/chunk-SWOOCAHN.js +4 -0
  12. package/out/{chunk-ARTS74PX.js → chunk-UETB6YE2.js} +1 -1
  13. package/out/{chunk-JHDPSG5Y.js → chunk-UK5UGFOX.js} +6 -6
  14. package/out/{chunk-WEPQK3AY.js → chunk-VV6YDN2D.js} +441 -145
  15. package/out/codecs.js +5 -5
  16. package/out/config.d.ts +6 -3
  17. package/out/i18n.d.ts +1 -1
  18. package/out/i18n.js +1 -1
  19. package/out/index.d.ts +1 -1
  20. package/out/index.js +5 -5
  21. package/out/internal.d.ts +1 -0
  22. package/out/internal.js +11 -11
  23. package/out/island.js +2 -2
  24. package/out/islandDependency.js +11 -11
  25. package/out/keywords/functions.d.ts +24 -24
  26. package/out/keywords/keywords.d.ts +2 -2
  27. package/out/keywords/phrases.d.ts +23 -23
  28. package/out/keywords/ts.js +2 -2
  29. package/out/locale.d.ts +1 -1
  30. package/out/locales/de.js +1 -1
  31. package/out/locales/en.js +3 -3
  32. package/out/match.d.ts +5 -3
  33. package/out/mutatesInput.js +2 -2
  34. package/out/parser/definition.d.ts +54 -3
  35. package/out/parser/shift/operand/unenclosed.d.ts +3 -1
  36. package/out/parser/shift/operand/unresolvable.d.ts +68 -0
  37. package/out/parser/shift/operator/bounds.d.ts +4 -1
  38. package/out/runtime.d.ts +34 -25
  39. package/out/runtime.js +2 -2
  40. package/out/runtimeDevelopment.js +63 -4
  41. package/out/scope.d.ts +4 -4
  42. package/out/standalone/artifact.d.ts +4 -0
  43. package/out/standalone/baking.d.ts +8 -1
  44. package/out/standalone/sites.d.ts +6 -3
  45. package/out/standalone/values.d.ts +2 -0
  46. package/out/type.d.ts +42 -5
  47. package/package.json +49 -6
  48. package/skills/arktype/SKILL.md +211 -92
  49. package/skills/arktype/references/migrating.md +990 -255
  50. package/skills/arktype/references/precompile.md +8 -5
  51. package/out/chunk-EDEN5UWG.js +0 -4
@@ -8,26 +8,29 @@ How to convert schemas from Zod (v3, v4 and Zod Mini), Valibot, TypeBox, Yup, Jo
8
8
 
9
9
  To move a whole project off Zod, or another library below, work through it in this order.
10
10
 
11
- 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.
12
- 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`.
13
- 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](#defaults-that-differ) has them for the other libraries:
14
- - `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"`.
15
- - 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.
16
- - A union of such objects throws a `ParseError` saying it's indeterminate unless a key tells them apart. Follow [Defaults that differ](#defaults-that-differ) for it, and keep the global setting: `"+": "ignore"` belongs only on the union's branches.
17
- - `.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)`.
18
- - `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.
19
- - Translate coercions and refinements literally, as in [Coercion is a parse](#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.
20
- - 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")`.
21
- - 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](#defaults-that-differ).
22
- - `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](#defaults-that-differ).
23
- - `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.
24
- - Keep custom messages. `.min(1, "Name is required")` becomes `type("string >= 1").configure({ message: "Name is required" })`.
11
+ 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. ArkType ships ES modules only, where Zod also ships CommonJS, so a CommonJS project needs a Node that can `require` one: 20.19, 22.12 or later, as [Setup](https://arktype.io/docs/intro/setup#configure-typescript) says.
12
+ 2. **Set Zod's defaults.** Write the config file from [Zod side by side](#zod-side-by-side), 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. Every object then removes undeclared keys, even where the code reads only declared ones, since parsed data often reaches a database or a response whole.
13
+ - Don't call `configure()` in a package others install, or in a project that already has ArkType Types of its own. It's global, so it would change those Types too, and in an app that installs the package it throws, `configure() must be called before any Type is created`, if the app created one first. There, create the converted Types with `$.type()`, from `const $ = scope({}, { exactOptionalPropertyTypes: false })`, and write `"+": "delete"` in each object, nested ones included.
14
+ - If `tsconfig.json` sets `exactOptionalPropertyTypes`, leave that option out of the config and write each `.optional()` key as `"key?": "T | undefined"`, and each `.default()` as [Defaults that differ](#defaults-that-differ) shows.
15
+ - If the project [precompiles](https://arktype.io/docs/precompile), also name the 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.
16
+ - If `package.json` sets `"sideEffects": false`, list the config file there instead, like `"sideEffects": ["./src/arktype.config.ts"]`. A bundler otherwise drops the import, and the built app runs without the config while unbundled tests pass.
17
+ - Migrating from another library? Set what its column of [Defaults that differ](#defaults-that-differ) says instead.
18
+ 3. **Convert each schema in place,** using the [tables](#zod). 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. The migrated schemas should accept, reject and return what the old ones did:
19
+ - **Objects.** `.passthrough()` and `z.looseObject()` are `"+": "ignore"`, and `.strict()` is `"+": "reject"`. A union throws a `ParseError` saying it's indeterminate where one of its objects overlaps another branch, like a second object with no literal key to tell them apart, or an array of the same object: write it as [Unions of objects](#unions-of-objects) shows. A `.merge()`, `.pick()`, `.omit()` or `.partial()` goes before the object's `.narrow()`, as in [Composing objects](#composing-objects).
20
+ - **Optional keys.** Before Zod 4.4, any key whose schema accepts `undefined` may be missing, so a `z.unknown()` key is `"key?": "unknown"` and a `z.any()` key is `"key?": "unknown.any"`; from 4.4, only `.optional()` and defaults let a key be missing, so they stay `key: "unknown"`. Check the version the project installs. In Zod 4, `.default(x).optional()` still fills in `x`, as does `.partial()` on a key with a default, so it's `key: T.default(x)`. In Zod 3 neither does: write the first as `"key?": "T"`, and for the second, call `.partial()` on a Type of the keys without their defaults, and `.merge()` the defaults into the full object. `"unknown.any"` infers `any` as Zod's did, so refinements that read its properties type-check without casts.
21
+ - **Coercions and refinements,** literally, as in [Coercion is a parse](#coercion-is-a-parse). `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, with its `path` as `relativePath`. A `.refine()` that only rejects a literal, like `z.boolean().refine(v => v, "Accept the terms")`, becomes that literal with a `message`; [Refinements](#refinements) has both.
22
+ - **Custom messages,** each as a `message`, as in [Custom messages](#custom-messages): `.min(1, "Name is required")` is `["string >= 1", "@", { message: "Name is required" }]` as a key's value, a value with a message for each of several checks names each check, and a `.refine(fn, "...")` message is `ctx.reject({ message: "..." })`. Never pass a Zod message to `ctx.reject()` as a string, to `ctx.mustBe()`, to `.describe()` or as `expected`, each of which writes `must be` before it.
23
+ - **Descriptions.** A `.describe(text)` on a schema given to a model or an OpenAPI generator, like a tool's `inputSchema`, stays one, as [Descriptions](#descriptions) shows, so the JSON Schema they read keeps it. Anywhere else it's a comment.
24
+ - **Strings.** Zod 4's `.url()` accepts what `URL.canParse` accepts and returns the string trimmed, and by 4.6 without the tabs and line breaks inside it, which 4.1 kept. `string.url` checks with `URL.canParse` too but returns the string as given, 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, `.min()`, `.max()` and `.length()` count code points, so an emoji counts once, where ArkType's bounds count UTF-16 code units, as `.length` does: where text may hold such characters, check the count in a `.narrow()`, as in [Defaults that differ](#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.
25
+ - **Arrays as objects.** `z.object()` and `z.record()` reject an array, which ArkType accepts as a `Record`, or as an object whose declared keys are all optional. Where every key is optional, reject arrays with a `.narrow()`, as in [Defaults that differ](#defaults-that-differ).
25
26
  4. **Update call sites.**
26
- - `X.parse(data)` becomes `X.assert(data)`, which throws.
27
- - `X.safeParse(data)` becomes `const out = X(data)`, then check `out instanceof type.errors`. `parseAsync` and `safeParseAsync` become the same, since ArkType is synchronous.
28
- - `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.
29
- - `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:
30
- - 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" })`.
27
+ - `X.parse(data)` becomes `X.assert(data)`, which throws a `TraversalError`. In a `catch`, `e instanceof ZodError` becomes `e instanceof TraversalError`, imported from `arktype`, `e.name === "ZodError"` becomes `e.name === "TraversalError"`, and `e.issues` becomes `e.arkErrors.issues`. A handler that sent the error whole, like `res.json(e)`, sent Zod's issues with it, where a `TraversalError` serializes as its `name` alone: send each issue's `path` and `message`.
28
+ - `X.safeParse(data)` becomes `const out = X(data)`. `!result.success` becomes `out instanceof type.errors`, `result.error` is `out`, and `result.data` is `out` once that check has failed. `parseAsync` and `safeParseAsync` become the same, since ArkType is synchronous.
29
+ - An issue keeps its `path` and `message`, which leaves out the path as Zod's does, like `must be an email address` where Zod's says `Invalid email address`. Its `code` is one of ArkType's, so code that switches on `"too_small"` or `"invalid_type"` needs [the codes they become](#issue-codes). `z.prettifyError(error)` becomes `out.summary`, which names each path, like `email must be an email address`, as does `fromError(error).message` from `zod-validation-error`; a caught `TraversalError`'s `message` is that summary already.
30
+ - An issue also holds the rejected value as `data`, which Zod's leaves out unless `reportInput` is set. Where code logs issues or returns them to a client, as `c.json(result.error)` does, send each issue's `path` and `message` instead, so a password that failed a check isn't written out.
31
+ - `z.infer<typeof X>` and `z.output` become `typeof X.infer`, and `z.input` becomes `typeof X.inferIn`.
32
+ - Don't add casts or `any`, not even `as unknown`. A helper typed with `z.ZodType`, `z.ZodTypeAny` or `z.ZodSchema` takes `type.Any`. One typed by what its schema returns, like `<T>(schema: z.ZodType<T>): T` or a `class Repo<T>`, keeps `T` and names what it calls: `schema: { assert: (data: unknown) => T }`, or `schema: (data: unknown) => T | ArkErrors` where it calls the Type. Every Type whose output is `T` fits, and call sites keep their type arguments. A `type.Any<T>` isn't that: its `T` isn't the output type once a Type has a default or a transform. Where the helper needs the Type itself, use `<S extends type.Any>(schema: S): S["infer"]`; there `schema(data)` is `any`, so annotate it: `const out: S["infer"] | type.errors = schema(data)`. A function that builds a schema from another, like `<T extends z.ZodType>(s: T) => s.nullable()`, becomes a generic, like `type("<t>", "t | null")`, as in [Schema factories](#schema-factories). Written as a method call on a `type.Any` parameter, `s.or("null")` type-checks and infers `any`.
33
+ - `error.flatten()` and `z.flattenError(error)` group messages by the first key of their path, so `tags[0]`'s are under `tags`. A `.strict()` object's unrecognized key is a form error in Zod, and in ArkType an error at that key, `must be removed`. Group `out.issues` the same way, which also works in a [precompiled](https://arktype.io/docs/precompile) build, where `flatByPath` isn't available, and build `z.treeifyError(error)`'s tree from each issue's `path`:
31
34
 
32
35
  ```ts
33
36
  // error.flatten() or z.flattenError(error)
@@ -37,29 +40,60 @@ for (const issue of out.issues) {
37
40
  if (issue.path.length === 0) formErrors.push(issue.message)
38
41
  else (fieldErrors[String(issue.path[0])] ??= []).push(issue.message)
39
42
  }
43
+
44
+ // z.treeifyError(error)
45
+ type Tree = {
46
+ errors: string[]
47
+ properties?: Record<string, Tree>
48
+ items?: Tree[]
49
+ }
50
+ const tree: Tree = { errors: [] }
51
+ for (const issue of out.issues) {
52
+ let node = tree
53
+ for (const key of issue.path) {
54
+ node =
55
+ typeof key === "number" ?
56
+ ((node.items ??= [])[key] ??= { errors: [] })
57
+ : ((node.properties ??= {})[String(key)] ??= { errors: [] })
58
+ }
59
+ node.errors.push(issue.message)
60
+ }
40
61
  ```
41
62
 
42
63
  5. **Swap integrations.** Most accept an ArkType type directly, through [Standard Schema](https://arktype.io/docs/standard-schema):
43
64
 
44
- | With Zod | With ArkType |
45
- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
46
- | `zodResolver(schema)` (react-hook-form) | `standardSchemaResolver(schema)` from `@hookform/resolvers/standard-schema` |
47
- | tRPC `.input(schema)`, `@t3-oss/env-*`, TanStack Form | the same call, given the ArkType type |
48
- | AI SDK 6+ `tool({ inputSchema })`, MCP SDK v2 `registerTool` | the same call, given the ArkType type, which also supplies the JSON Schema |
49
- | AI SDK 5 `tool({ inputSchema })` | `jsonSchema<typeof T.infer>(T.toJsonSchema(), { validate })`, where `validate` returns `{ success: true, value }` or `{ success: false, error }` |
50
- | `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 }` |
51
- | `@hono/zod-openapi` | `hono-openapi`: `describeRoute`, `validator` and `resolver` |
52
- | `zod-to-json-schema`, `z.toJSONSchema(schema)` | `schema.toJsonSchema()` |
53
- | `@asteasolutions/zod-to-openapi` | `schema.toJsonSchema({ target: "openapi-3.0" })` for each Schema Object in your OpenAPI document; see below |
54
- | `drizzle-zod` | `drizzle-arktype` |
55
- | a library that accepts only Zod | keep Zod for that call, and say so |
65
+ | With Zod | With ArkType |
66
+ | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
67
+ | `zodResolver(schema)` (react-hook-form) | `standardSchemaResolver(schema)` from `@hookform/resolvers/standard-schema` |
68
+ | tRPC `.input(schema)`, TanStack Form, next-safe-action `.inputSchema(schema)`, OpenAI Agents SDK `tool({ parameters })` | the same call, given the ArkType type |
69
+ | `validateSearch: zodValidator(schema)` (TanStack Router) | `validateSearch: T`, with no adapter; the adapter's `fallback(schema, x)` is a [fallback](#fallbacks) |
70
+ | `createEnv` from `@t3-oss/env-*` | the same call, with a Type for each variable. Each is validated alone and gets `undefined` when unset, so use the rows for [`.optional()` and `.default(x)` anywhere else](#objects) |
71
+ | a tRPC `errorFormatter` checking `error.cause instanceof ZodError` | `error.cause instanceof TraversalError`; for `error.cause.flatten()`, group `error.cause.arkErrors.issues` as step 4 shows, or send `flatMessagesByPath(error.cause.arkErrors)`, keyed by each full path |
72
+ | AI SDK 6+ `tool({ inputSchema })`, MCP SDK v2 `registerTool` | the same call, given the ArkType type, which also supplies the JSON Schema |
73
+ | AI SDK 5 `tool({ inputSchema })` | `jsonSchema<typeof T.infer>(T.toJsonSchema(), { validate })`, where `validate` returns `{ success: true, value }` or `{ success: false, error }` |
74
+ | `zodResponseFormat`, `zodTextFormat`, `zodFunction` (OpenAI SDK) | `standardResponseFormat`, `standardTextFormat`, `standardFunction` from `openai/helpers/standard-schema`, there from 6.49. Write a key with a default as required, without it, as [OpenAI SDK](https://arktype.io/docs/integrations#openai-sdk) says. An invalid response throws an `OpenAIError`, not a `ZodError` |
75
+ | `zodOutputFormat`, `betaZodTool` (Anthropic SDK) | `betaStandardSchemaOutputFormat`, passed to `client.beta.messages.parse`, and `betaStandardSchemaTool`, from `@anthropic-ai/sdk/helpers/beta/standard-schema`, there from 0.121; see [Anthropic SDK](https://arktype.io/docs/integrations#anthropic-sdk) |
76
+ | LangChain `tool(fn, { schema })` | `schema: T.toJsonSchema()`, with `T.assert(input)` in the function. Given the Type itself, `tool()` type-checks, then throws a `TypeError` each time the tool runs |
77
+ | `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 }` |
78
+ | `zod4(schema)`, `zod4Client(schema)` (Superforms) | `standard(T, { jsonSchema: T.toJsonSchema() })`, `standardClient(T)` from `sveltekit-superforms/adapters` |
79
+ | `fastify-type-provider-zod` | a validator compiler, a serializer compiler and a type provider of your own, as [Fastify](https://arktype.io/docs/integrations#fastify) shows |
80
+ | `@hono/zod-openapi` | `hono-openapi`: `describeRoute`, `validator` and `resolver`; for a schema named with `.openapi("User")`, see [OpenAPI documents](#openapi-documents) |
81
+ | `zod-to-json-schema`, `z.toJSONSchema(schema)` | `schema.toJsonSchema()`, which leaves a key with a default out of `required` where Zod lists it; for `{ io: "input" }`, `schema.in.toJsonSchema()` |
82
+ | `@asteasolutions/zod-to-openapi` | `schema.toJsonSchema({ target: "openapi-3.0" })` for each Schema Object in your OpenAPI document; see [OpenAPI documents](#openapi-documents) |
83
+ | `drizzle-zod` | `drizzle-arktype` |
84
+ | `zod-fast-check`, `@anatine/zod-mock`, `zocker` (test data from a schema) | `arkToArbitrary(T)` from [`@ark/fast-check`](https://arktype.io/docs/fast-check), which generates the Type's input and lists what it can't generate; `fc.sample(arkToArbitrary(T), 1)[0]` is one value |
85
+ | a library that accepts only Zod | keep Zod for that call, and say so |
56
86
 
57
87
  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`.
58
88
 
89
+ For a library the table doesn't list, pass it the Type, then call it once with invalid data before relying on it: type-checking isn't proof, as LangChain's `tool()` shows. If the invalid data isn't rejected with the Type's errors, keep Zod for that call.
90
+
91
+ Take the Standard Schema route in the table over an adapter written for arktype 2. `@hono/arktype-validator`, Superforms' `arktype()`, `arktypeResolver` before `@hookform/resolvers` 5, `@arkenv/core` and `@typeschema/arktype` [fail on invalid input](https://arktype.io/docs/upgrading#adapters-written-for-arktype-2) until they're updated.
92
+
59
93
  Without casts:
60
94
 
61
- - `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.
62
- - A `fallback` declared apart from the `toJsonSchema()` call is a `ToJsonSchema.FallbackOption` (`import type { ToJsonSchema } from "arktype"`).
95
+ - `toJsonSchema()` returns a `JsonSchema`, the type to give the document's Schema Objects (`import type { JsonSchema } from "arktype"`).
96
+ - A `fallback` declared apart from the `toJsonSchema()` call is a `ToJsonSchema.FallbackOption` (`import type { ToJsonSchema } from "arktype"`). A [precompiled](https://arktype.io/docs/precompile) build also needs each handler's parameter annotated there, like `(ctx: ToJsonSchema.MorphContext)`.
63
97
  - The MCP SDK finds a prompt argument's completer through Zod's `.shape`, so give `argsSchema` one, as below.
64
98
 
65
99
  ```ts
@@ -77,21 +111,21 @@ const argsSchema = {
77
111
  }
78
112
  ```
79
113
 
80
- 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](#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](#how-to-convert) shows a check that their types match too.
114
+ 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](#defaults-that-differ) lists: a missing key, a key present as `undefined`, an undeclared key, a wrong type, an array in place of an object, an empty string and a value at each bound. Fix each difference in the schema, then delete the scratch files. [How to convert](#how-to-convert) shows a check that their types match too.
81
115
  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.
82
- 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.
83
- 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](#precompile) below.
84
- 10. **Report** what still behaves differently, if anything, such as error message text, any snapshot you reordered, and any dependency you kept Zod for.
116
+ 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 Jest fails with `Must use import to load ES Module`, naming arktype, [have it transform arktype's packages](https://arktype.io/docs/faq#why-does-jest-say-must-use-import-to-load-es-module), which ship ES modules only. 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, an issue `code` 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.
117
+ 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 2 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](#precompile) below.
118
+ 10. **Report** what still behaves differently, if anything, such as error message text, any snapshot you reordered, and any dependency you kept Zod for. Where the code ships to a browser and wasn't precompiled, say that arktype's parser now ships with it, which [precompiling](#precompile) removes.
85
119
 
86
120
  ## Zod side by side
87
121
 
88
- A Zod schema and its ArkType equivalent:
122
+ A Zod schema:
89
123
 
90
124
  ```ts
91
125
  import { z } from "zod"
92
126
 
93
127
  const User = z.object({
94
- name: z.string().min(1),
128
+ name: z.string().min(1, "Name is required"),
95
129
  email: z.email(),
96
130
  age: z.number().int().nonnegative().optional(),
97
131
  role: z.enum(["admin", "member"]).default("member")
@@ -101,19 +135,19 @@ type User = z.infer<typeof User>
101
135
 
102
136
  const result = User.safeParse(data)
103
137
 
104
- if (!result.success) console.error(result.error.issues)
138
+ if (!result.success) console.error(z.prettifyError(result.error))
105
139
  ```
106
140
 
141
+ The same in ArkType:
142
+
107
143
  ```ts
144
+ import "./arktype.config.ts"
108
145
  import { type } from "arktype"
109
146
 
110
147
  const User = type({
111
- // z.object() removes undeclared keys
112
- "+": "delete",
113
- name: "string >= 1",
148
+ name: ["string >= 1", "@", { message: "Name is required" }],
114
149
  email: "string.email",
115
- // .optional() accepts undefined too
116
- "age?": "number.integer >= 0 | undefined",
150
+ "age?": "number.integer >= 0",
117
151
  role: "'admin' | 'member' = 'member'"
118
152
  })
119
153
 
@@ -121,74 +155,258 @@ type User = typeof User.infer
121
155
 
122
156
  const out = User(data)
123
157
 
124
- if (out instanceof type.errors) console.error(out.issues)
158
+ if (out instanceof type.errors) console.error(out.summary)
159
+ ```
160
+
161
+ Two of Zod's defaults differ from ArkType's, and the config file it imports sets both for every Type in the project:
162
+
163
+ ```ts
164
+ import { configure } from "arktype/config"
165
+
166
+ configure({
167
+ // z.object() removes undeclared keys, where ArkType keeps them
168
+ onUndeclaredKey: "delete",
169
+ // .optional() accepts undefined and .default() replaces it,
170
+ // where ArkType's optional keys and defaults are for missing keys only
171
+ exactOptionalPropertyTypes: false
172
+ })
125
173
  ```
126
174
 
127
- `.parse(data)` is `User.assert(data)`. The [Zod table](#zod) maps the rest of the API, and [Defaults that differ](#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.
175
+ Import it before anything creates a Type. To convert one schema without it, say both in the definition: `"+": "delete"` in each object, and `"age?": "number.integer >= 0 | undefined"`. [Defaults that differ](#defaults-that-differ) has every default to check, for each library.
128
176
 
129
177
  ## Zod
130
178
 
131
- 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)`.
132
-
133
- | Zod | ArkType |
134
- | ------------------------------------------------------- | ------------------------------------------------------------------------------------ |
135
- | `z.string()`, `z.number()`, `z.boolean()`, `z.null()` | `"string"`, `"number"`, `"boolean"`, `"null"` |
136
- | `z.bigint()`, `z.symbol()`, `z.undefined()`, `z.void()` | `"bigint"`, `"symbol"`, `"undefined"`, `"undefined"` |
137
- | `z.unknown()`, `z.any()`, `z.never()` | `"unknown"`, `"unknown.any"`, `"never"` |
138
- | `z.literal("a")`, `z.literal(0.5)` | `"'a'"`, `"0.5"` |
139
- | `z.enum(["a", "b"])` | `"'a' \| 'b'"` or `type.enumerated("a", "b")` |
140
- | `z.nativeEnum(E)`, `z.enum(E)` | `type.valueOf(E)` |
141
- | `z.object({ ... })` | `type({ ... })`, nested objects as plain objects |
142
- | `.optional()` on a property | `"key?": "T \| undefined"` |
143
- | `.optional()` anywhere else | `"T \| undefined"` or `T.or("undefined")` |
144
- | `.nullable()`, `.nullish()` | `"T \| null"`, `"key?": "T \| null \| undefined"` |
145
- | `.default(x)` on a property | `key: "number = 0"` or `key: T.default(x)` |
146
- | `.catch(x)` | a `.pipe()` that returns `x` for invalid input, see [Fallbacks](#semantics-to-check) |
147
- | `z.array(T)`, `.min(1)`, `.nonempty()` | `"T[]"` or `T.array()`, `"string[] >= 1"` |
148
- | `z.array(T).min(1)`, `T` a Type in a variable | `T.array().atLeastLength(1)` |
149
- | `z.tuple([A, B])`, `.rest(C)` | `[A, B]`, `[A, B, "...", "C[]"]` |
150
- | `z.union([A, B])`, `A.or(B)`, `z.discriminatedUnion` | `A.or(B)`, `"A \| B"` |
151
- | `z.intersection(A, B)`, `A.and(B)` | `A.and(B)` |
152
- | `z.record(z.string(), T)` | `"Record<string, T>"` or `{ "[string]": T }` |
153
- | `z.record(z.enum(["a", "b"]), T)`, `z.partialRecord` | `{ a: T, b: T }`, `{ "a?": T, "b?": T }` |
154
- | `z.set(T)`, `z.map(K, V)` | `"Set"`, `"Map"`, with a `.narrow()` that checks the entries |
155
- | `.extend({ ... })`, `.merge(B)` | `.merge({ ... })` |
156
- | `.pick`, `.omit`, `.partial`, `.required`, `.keyof` | same names |
157
- | `.array()`, `.readonly()` | same names |
158
- | `.strict()`, `z.strictObject` | `"+": "reject"` |
159
- | `.passthrough()`, `z.looseObject` | the default |
160
- | `.strip()`, the default `z.object` | `"+": "delete"` |
161
- | `.catchall(T)` | `"[/^(?!a$\|b$)/]": T`, `a` and `b` the declared keys |
162
- | `z.lazy(() => T)` | a scope or `this` |
163
- | `.min(n)` / `.max(n)` / `.length(n)` on strings | `"string >= n"`, `"string <= n"`, `"string == n"` |
164
- | `.nonempty()` on strings | `"string > 0"` |
165
- | `.startsWith("a")`, `.endsWith("a")`, `.includes("a")` | `/^a/`, `/a$/`, `/a/`, escaping regex characters |
166
- | `.int()` | `"number.integer & number.safe"`, or `"number.integer"` in Zod 3 |
167
- | `.positive()`, `.nonnegative()`, `.gt(n)` | `"number > 0"`, `"number >= 0"`, `"number > n"` |
168
- | `.min(n)` / `.max(n)` / `.lt(n)` on numbers | `"number >= n"`, `"number <= n"`, `"number < n"` |
169
- | `.multipleOf(n)` | `"number % n"` |
170
- | `.email()`, `.url()`, `.uuid()`, `.regex(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
171
- | `.ip()` (Zod 3), `z.ipv4()`, `z.ipv6()` | `"string.ip"`, `"string.ip.v4"`, `"string.ip.v6"` |
172
- | `.datetime()`, `z.iso.datetime()` | `"string.date.iso"` |
173
- | `.trim()`, `.toLowerCase()`, `.toUpperCase()` | `"string.trim"`, `"string.lower"`, `"string.upper"` |
174
- | `z.date()`, `z.instanceof(C)` | `"Date"`, `type.instanceOf(C)` |
175
- | `.refine(fn, msg)`, `.superRefine(fn)` | `.narrow((v, ctx) => fn(v) \|\| ctx.reject({ message: msg }))` |
176
- | `.transform(fn)`, `.pipe(T)` | `.pipe(fn)`, `.to(T)` |
177
- | `z.preprocess(fn, T)` | `type("unknown").pipe(fn).to(T)` |
178
- | `z.coerce.number()`, `z.coerce.date()` | `type("unknown").pipe(Number).to("number")`, see [Coercion](#semantics-to-check) |
179
- | `z.coerce.string()`, `z.coerce.boolean()` | `type("unknown").pipe(String)`, `type("unknown").pipe(Boolean)` |
180
- | `z.custom<T>(fn)` | `type("unknown").narrow((v): v is T => fn(v))` |
181
- | `.brand<"Id">()` | `.brand("Id")` or `"string#Id"` |
182
- | `.describe(text)`, `.meta({ title })` | a comment or `.configure({ title: text })` |
183
- | `{ message }`, `{ error }`, `required_error` | `.configure({ message })`, or `.describe(...)` for "must be ..." |
184
- | `z.infer`, `z.output`, `z.input` | `typeof T.infer`, `typeof T.inferIn` |
185
- | `const T: z.ZodType<X> = ...` | no annotation: delete `X` and use `typeof T.infer` |
186
- | `.parse(x)`, `.safeParse(x)` | `T.assert(x)`, `T(x)` then `instanceof type.errors` |
187
- | `.parseAsync(x)`, `.safeParseAsync(x)` | the same, since ArkType is synchronous |
188
- | `ZodError`, `error.issues` | `type.errors`, `out.issues` |
189
- | `z.prettifyError(error)` | `out.summary` |
190
- | `error.flatten()`, `z.flattenError(error)` | `out.issues` grouped by key, see [Update call sites](#migrating-a-project) |
191
- | `z.ZodTypeAny` in a helper's signature | `type.Any` |
179
+ The ArkType column assumes [the two options above](#zod-side-by-side). In a string, `T` stands for a keyword or expression, as in `"string | null"`. A string can't name a variable, so for a Type in one, use the chained form, like `T.or("null")` or `T.array()`, or put the Type itself where the string would go, as in `{ "[string]": T }`.
180
+
181
+ Zod Mini spells most methods as functions, so `z.optional(z.string())` maps like `z.string().optional()`, `z.string().check(z.minLength(1))` like `z.string().min(1)`, `z._default(T, x)` like `T.default(x)`, `z.extend(A, { ... })` like `A.extend({ ... })` and `z.safeParse(T, x)` like `T.safeParse(x)`.
182
+
183
+ ### Primitives and literals
184
+
185
+ | Zod | ArkType |
186
+ | --------------------------------------------------------------------- | ----------------------------------------------------------- |
187
+ | `z.string()`, `z.number()`, `z.boolean()`, `z.bigint()`, `z.symbol()` | `"string"`, `"number"`, `"boolean"`, `"bigint"`, `"symbol"` |
188
+ | `z.null()`, `z.undefined()`, `z.void()` | `"null"`, `"undefined"`, `"undefined"` |
189
+ | `z.unknown()`, `z.any()`, `z.never()` | `"unknown"`, `"unknown.any"`, `"never"` |
190
+ | `z.date()`, `z.instanceof(C)` | `"Date"`, `type.instanceOf(C)` |
191
+ | `z.literal("a")`, `z.literal(0.5)`, `z.literal(true)` | `"'a'"`, `"0.5"`, `"true"` |
192
+ | `z.enum(["a", "b"])`, `z.literal(["a", "b"])` | `"'a' \| 'b'"` or `type.enumerated("a", "b")` |
193
+ | `z.enum(values)`, `values` an `as const` array | `type.enumerated(...values)` |
194
+ | `z.nativeEnum(E)`, `z.enum(E)` | `type.valueOf(E)` |
195
+ | `z.json()` | `"string \| number \| boolean \| null \| object.json"` |
196
+
197
+ ### Strings
198
+
199
+ | Zod | ArkType |
200
+ | ------------------------------------------------------ | ------------------------------------------------------------------------------------ |
201
+ | `.min(n)`, `.max(n)`, `.length(n)` | `"string >= n"`, `"string <= n"`, `"string == n"` |
202
+ | `.min(1).max(100)`, `.nonempty()` | `"1 <= string <= 100"`, `"string > 0"` |
203
+ | `z.email()`, `z.url()`, `z.uuid()`, `z.base64()` | `"string.email"`, `"string.url"`, `"string.uuid"`, `"string.base64"` |
204
+ | `z.string().email()` and the other chained formats | the same keywords |
205
+ | `.regex(/^a/)` | `/^a/`, or `"/^a/"` in a string |
206
+ | `.startsWith("a")`, `.endsWith("a")`, `.includes("a")` | `/^a/`, `/a$/`, `/a/`, escaping regex characters |
207
+ | `z.ipv4()`, `z.ipv6()`, `.ip()` (Zod 3) | `"string.ip.v4"`, `"string.ip.v6"`, `"string.ip"` |
208
+ | `z.creditCard()` | `"string.creditCard"`, which rejects spaces and hyphens |
209
+ | `z.iso.datetime()`, `.datetime()`, `z.iso.date()` | `"string.date.iso"`, which accepts more; see [Dates and formats](#dates-and-formats) |
210
+ | `.trim()`, `.toLowerCase()`, `.toUpperCase()` | `"string.trim"`, `"string.lower"`, `"string.upper"` |
211
+ | `.trim().min(1)`, a check after a transform | `type("string.trim").to("string >= 1")` |
212
+
213
+ ### Numbers
214
+
215
+ | Zod | ArkType |
216
+ | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
217
+ | `.int()`, `z.int()` | `"number.integer & number.safe"`, or `"number.integer"` in Zod 3 |
218
+ | `.positive()`, `.nonnegative()`, `.negative()`, `.nonpositive()` | `"number > 0"`, `"number >= 0"`, `"number < 0"`, `"number <= 0"` |
219
+ | `.gt(n)`, `.gte(n)` or `.min(n)` | `"number > n"`, `"number >= n"` |
220
+ | `.lt(n)`, `.lte(n)` or `.max(n)` | `"number < n"`, `"number <= n"` |
221
+ | `.int().min(1).max(5)` | `"1 <= number.integer <= 5"` |
222
+ | `.multipleOf(5)`, `.step(5)` | `"number % 5"`, for an integer divisor |
223
+ | `.multipleOf(0.01)` | `.narrow((n, ctx) => Math.round(n * 100) / 100 === n \|\| ctx.mustBe("a multiple of 0.01"))` |
224
+ | `.finite()` | `"number"`, which already rejects `Infinity` and `NaN` |
225
+ | `.safe()` (Zod 3) | `"number.safe"` |
226
+
227
+ ### Objects
228
+
229
+ | Zod | ArkType |
230
+ | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
231
+ | `z.object({ ... })` | `type({ ... })`, nested objects as plain objects |
232
+ | `.optional()` on a property | `"key?": "T"`, or `key: T.optional()` for a Type in a variable |
233
+ | `.optional()` anywhere else | `"T \| undefined"` or `T.or("undefined")` |
234
+ | `.exactOptional()`, `.exactPartial()` | `"key?": "T"`, `.partial()`, without `exactOptionalPropertyTypes: false` in the config |
235
+ | `.nullable()`, `.nullish()` | `"T \| null"`, `"key?": "T \| null"` |
236
+ | `.default(x)` on a property | `key: "number = 0"` or `key: T.default(x)` |
237
+ | `.default([])`, `.default({})` | `key: "string[] = []"`, `key: "object = {}"`, or `key: T.default(() => [])` for a Type: a function |
238
+ | `.default(x)` anywhere else, like one env variable's | `type("T \| undefined").pipe(v => v ?? x)`: a default belongs to a key |
239
+ | `.catch(x)` | a `.pipe()` that returns `x` for invalid input, see [Fallbacks](#fallbacks) |
240
+ | `.extend({ ... })`, `.safeExtend({ ... })`, `.merge(B)` | `.merge({ ... })`, `.merge(B)` |
241
+ | `.pick({ a: true })`, `.omit({ a: true })` | `.pick("a")`, `.omit("a")` |
242
+ | `.partial()`, `.required()`, `.keyof()` | same names |
243
+ | `.required()` on keys that were optional or defaulted | `.merge()` them in without `?`: its keys still take `undefined` once configured, and lose defaults |
244
+ | `.deepPartial()` (Zod 3), `z.deepPartial(T)` | no equivalent: call `.partial()` on each nested object's Type |
245
+ | any of those on a schema with a `.refine()` | on the object before its `.narrow()`, see [Composing objects](#composing-objects) |
246
+ | `T.shape.a`, `Object.keys(T.shape)` | `T.get("a")`, `T.props.map(prop => prop.key)` |
247
+ | `z.object({ a: T.shape.a, b: B })`, to reuse a key | `T.pick("a").merge({ b: B })`: `T.get("a")` is `a`'s Type without its `?` or default |
248
+ | `.strict()`, `z.strictObject` | `"+": "reject"` in the object, or `T.onUndeclaredKey("reject")` |
249
+ | `.passthrough()`, `.loose()`, `z.looseObject` | `"+": "ignore"` in the object, or `T.onUndeclaredKey("ignore")` |
250
+ | the same, where code reads the extra keys | `"[string]": "unknown"` beside it, which infers the index signature Zod's type had |
251
+ | `.strip()`, the default `z.object` | the default once configured, or `"+": "delete"` |
252
+ | `.catchall(T)` | `"[/^(?!a$\|b$)/]": T`, `a` and `b` the declared keys |
253
+
254
+ ### Arrays, tuples and records
255
+
256
+ | Zod | ArkType |
257
+ | ---------------------------------------------------- | ----------------------------------------------------------------------------------- |
258
+ | `z.array(z.string())`, `z.array(T)` | `"string[]"`, `T.array()` for a Type in a variable |
259
+ | `.min(1)` or `.nonempty()`, `.max(5)`, `.length(2)` | `"string[] >= 1"`, `"string[] <= 5"`, `"string[] == 2"` |
260
+ | the same after `T.array()` | `.atLeastLength(1)`, `.atMostLength(5)`, `.exactlyLength(2)` |
261
+ | `z.tuple([A, B])`, `.rest(C)` | `[A, B]`, `[A, B, "...", "C[]"]` |
262
+ | `z.tuple([A, B.optional()])` | `[A, "B?"]`, or `[A, "(B \| undefined)?"]` to accept `undefined` in its place |
263
+ | `z.record(z.string(), T)` | `"Record<string, T>"` or `{ "[string]": T }` |
264
+ | an array given to `z.record(z.string(), T)` | passes if its elements are `T`: see [Defaults that differ](#defaults-that-differ) |
265
+ | `z.record(z.enum(["a", "b"]), T)`, `z.partialRecord` | `{ "+": "reject", a: T, b: T }`, the same with `"a?"` and `"b?"` |
266
+ | `z.record(z.string().regex(/^[A-Z_]+$/), T)` | `{ "+": "reject", "[/^[A-Z_]+$/]": T }`, since Zod rejects a key that doesn't match |
267
+ | `z.set(T)`, `z.map(K, V)` | `"Set"`, `"Map"` and a `.narrow()` on the entries, typed `(s): s is Set<T> =>` |
268
+ | `.readonly()` | `.readonly()` |
269
+
270
+ ### Unions and recursion
271
+
272
+ | Zod | ArkType |
273
+ | -------------------------------------- | ------------------------------------------------------------------------------ |
274
+ | `z.union([A, B])`, `A.or(B)` | `A.or(B)`, `"string \| number"` |
275
+ | `z.discriminatedUnion("kind", [A, B])` | `A.or(B)`: ArkType finds the discriminant itself |
276
+ | `z.union([Item, z.array(Item)])` | a `.pipe()` that picks the branch, see [Unions of objects](#unions-of-objects) |
277
+ | `z.intersection(A, B)`, `A.and(B)` | `A.and(B)` |
278
+ | `z.lazy(() => T)`, a getter | `"this"` or a scope, see [Recursion](#recursion-needs-no-annotation) |
279
+
280
+ ### Refinements and transforms
281
+
282
+ | Zod | ArkType |
283
+ | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
284
+ | `.refine(fn, "Message")` | `.narrow((v, ctx) => fn(v) \|\| ctx.reject({ message: "Message" }))` |
285
+ | `.refine(fn, { message, path: ["key"] })` | the same, with `ctx.reject({ message, relativePath: ["key"] })` |
286
+ | `.superRefine(fn)`, `.check(fn)`, several `addIssue`s | `ctx.error({ message, relativePath })` for each, see [Refinements](#refinements) |
287
+ | `.transform(fn)`, `.pipe(T)` | `.pipe(fn)`, `.to(T)` |
288
+ | a transform that fails: `ctx.addIssue(...)`, `return z.NEVER` | `.pipe((v, ctx) => ok ? result : ctx.error({ message }))` |
289
+ | `z.preprocess(fn, T)` | `type("unknown").pipe(fn).to(T)` |
290
+ | `z.coerce.number()`, `z.coerce.date()` | `type("unknown").pipe(Number).to("number")`, see [Coercion](#coercion-is-a-parse) |
291
+ | `z.coerce.string()`, `z.coerce.boolean()` | `type("unknown").pipe(String)`, `type("unknown").pipe(Boolean)` |
292
+ | `z.stringbool()` | a `.pipe()` over the strings you accept, see [Coercion](#coercion-is-a-parse) |
293
+ | `z.custom<T>(fn)`, `z.custom<T>(fn, "Message")` | `type("unknown").narrow((v): v is T => fn(v))`, then `.configure({ message: "Message" })` |
294
+ | `.brand<"Id">()` | `.brand("Id")` or `"string#Id"` |
295
+ | `z.codec(In, Out, { decode, encode })` | `codec(In, Out, { decode, encode })` from `arktype/codecs` |
296
+ | `T.decode(x)`, `T.encode(x)`, `T.safeEncode(x)` | `T.assert(x)`, `T.encode.assert(x)`, `T.encode(x)` |
297
+ | `z.input(T)`, `z.output(T)`, as schemas | `T.in`, `T.out` |
298
+ | `.describe(text)`, `.meta({ description })` | `.describe(text)` where a model or an OpenAPI document reads it, else a comment; see [Descriptions](#descriptions) |
299
+
300
+ ### Error messages
301
+
302
+ Every row is in [Custom messages](#custom-messages), with what each says.
303
+
304
+ | Zod | ArkType |
305
+ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
306
+ | `.min(1, "Name is required")`, `{ message }` | `["string >= 1", "@", { message: "Name is required" }]` as a key's value |
307
+ | the same, on a Type | `type("string >= 1").configure({ message: "Name is required" })` |
308
+ | `.min(8, "Too short").regex(r, "Add a number")` | `.configure({ message: "Too short" }, "minLength")`, then the same for `"pattern"` |
309
+ | `z.string({ error: "Enter a name" })` | `["string", "@", { message: "Enter a name" }]`, which a missing key says too |
310
+ | `required_error`, `invalid_type_error` (Zod 3) | `.configure({ message }, "self")`, `.configure({ message }, "domain")` |
311
+ | `.refine(fn, "Message")` | `ctx.reject({ message: "Message" })` |
312
+ | `error: issue => ...`, `z.config({ customError })` | `message: error => ...`, or [by code](https://arktype.io/docs/configuration#by-code) in `configure` |
313
+ | `errorMap`, `z.setErrorMap(fn)` (Zod 3) | the same: `message: error => ...` on the Type, or by code in `configure` |
314
+
315
+ ### Types and parsing
316
+
317
+ | Zod | ArkType |
318
+ | --------------------------------------------------------- | -------------------------------------------------------------------------------------- |
319
+ | `z.infer<typeof T>`, `z.output`, `z.input` | `typeof T.infer`, `typeof T.infer`, `typeof T.inferIn` |
320
+ | `const T: z.ZodType<X> = ...` | no annotation: delete `X` and use `typeof T.infer`, or the next row to keep `X` |
321
+ | `satisfies z.ZodType<X>`, `z.toZod<X>()`: `X` must stay | [`type.declare<X>().type({ ... })`](https://arktype.io/docs/declare) |
322
+ | `z.ZodType`, `z.ZodTypeAny` in a helper's signature | `type.Any` |
323
+ | `schema: z.ZodType<X>`, any schema that returns `X` | `schema: { assert: (data: unknown) => X }`: see [step 4](#migrating-a-project) |
324
+ | `T.parse(x)` | `T.assert(x)` |
325
+ | `T.safeParse(x)`, then `result.success` and `result.data` | `const out = T(x)`, then `out instanceof type.errors`, else `out` is the data |
326
+ | `.parseAsync(x)`, `.safeParseAsync(x)` | the same, since ArkType is synchronous |
327
+ | `T.validate(x)`, `z.validate(T, x)` | `T.allows(x)` |
328
+ | `z.compile(T)` | `T`: a Type compiles itself, and a build can [precompile](#precompile) it |
329
+ | `result.error.issues`, `issue.path`, `issue.message` | `out.issues`, `issue.path`, `issue.message` |
330
+ | `error.errors` (Zod 3), `z.ZodIssue`, `z.ZodError` types | `out.issues`, and the types `ArkError` and `ArkErrors` from `arktype` |
331
+ | `issue.code`, like `"too_small"` | `issue.code`, with [ArkType's codes](#issue-codes), like `"minLength"` |
332
+ | `catch (e) { if (e instanceof ZodError) ... }` | `e instanceof TraversalError`, whose `e.arkErrors.issues` holds them |
333
+ | `z.prettifyError(error)` | `out.summary` |
334
+ | `error.flatten()`, `z.flattenError(error)` | group `out.issues` by key, see [Update call sites](#migrating-a-project) |
335
+ | `z.treeifyError(error)`, `error.format()` | build the tree from each issue's `path`, see [Update call sites](#migrating-a-project) |
336
+
337
+ ### Issue codes
338
+
339
+ Code that reads `issue.code`, like an API's error translator or a `customError` map, needs ArkType's [codes](https://arktype.io/docs/errors#error-codes):
340
+
341
+ | Zod | ArkType |
342
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------ |
343
+ | `invalid_type` | `required`, `domain`, `proto` or `discriminant`, as below |
344
+ | `invalid_value` | `unit` for one literal, `discriminant` for several |
345
+ | `invalid_union` | `discriminant`, or `union` where neither a type nor a literal key tells the branches apart |
346
+ | `too_small`, `too_big` for a number | `min`, `max` |
347
+ | `too_small`, `too_big` for a string or array | `minLength`, `maxLength`, or `exactLength` for `.length(n)` and a tuple |
348
+ | `too_small`, `too_big` for a `Date` | `after`, `before` |
349
+ | `not_multiple_of`, `.int()`'s `invalid_type` | `divisor` |
350
+ | `invalid_format` | `pattern`, or `predicate` for `string.url` |
351
+ | `unrecognized_keys` | `undeclared`, an issue for each key, at the key |
352
+ | `custom` | `predicate` |
353
+
354
+ A `z.union()` of objects often reports one `invalid_union` issue at the union's own path, with each branch's issues inside it. Here a literal key like `type` picks the branch, as in a `z.discriminatedUnion()`, so the issues are that branch's own, each at its own path, and a value that matches no branch gets a `discriminant` issue at that key.
355
+
356
+ Zod's `minimum` and `maximum` are `issue.rule`. A wrong type is `required` for a missing key, `domain` for a primitive or an object, `proto` for an array, a `Date` or another class, and `discriminant` where the value may also be `null` or `undefined`, which is a boolean's and an enum's code too. So one message for every wrong type, as a `customError` gives `invalid_type`, is configured under four codes:
357
+
358
+ ```ts
359
+ import { configure } from "arktype/config"
360
+
361
+ const wrongType = { message: "Wrong type" }
362
+
363
+ configure({
364
+ onUndeclaredKey: "delete",
365
+ exactOptionalPropertyTypes: false,
366
+ required: wrongType,
367
+ domain: wrongType,
368
+ proto: wrongType,
369
+ discriminant: {
370
+ // "unit" for a boolean or an enum, which literals tell apart
371
+ message: error =>
372
+ error.discriminantKind === "domain" ?
373
+ "Wrong type"
374
+ : `Expected ${error.expected}`
375
+ }
376
+ })
377
+ ```
378
+
379
+ A [precompiled](https://arktype.io/docs/precompile) build takes a function for the table's other codes, but only a string for `discriminant` and `union`, so a boolean's or an enum's miss says it too, and no message for `predicate`: pass a narrow's text to `ctx.reject()`.
380
+
381
+ ### Less common
382
+
383
+ | Zod | ArkType |
384
+ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
385
+ | `z.hex()`, `z.base64url()`, `z.uuidv4()` | `"string.hex"`, `"string.base64.url"`, `"string.uuid.v4"` |
386
+ | `z.nanoid()`, `z.ulid()`, `z.cuid2()`, `z.e164()`, `z.guid()` | no keyword: a regex, like the one Zod exports as `z.regexes.ulid` |
387
+ | `z.iso.time()`, `z.iso.duration()` | the same, from `z.regexes.time({})` and `z.regexes.duration` |
388
+ | `z.hostname()`, `z.cidrv4()`, `z.cidrv6()` | the same, from `z.regexes.hostname`, `z.regexes.cidrv4` and `z.regexes.cidrv6` |
389
+ | `z.httpUrl()` | `type("string.url").and(/^https?:\/\//i)` |
390
+ | `.lowercase()`, `.uppercase()`, `.normalize()` | `"string.lower.preformatted"`, `"string.upper.preformatted"`, `"string.normalize"` |
391
+ | `z.templateLiteral(["user-", z.number()])` | a regex, like `/^user-\d+$/` |
392
+ | `z.int32()`, `z.uint32()` | `"-2147483648 <= number.integer <= 2147483647"`, `"0 <= number.integer <= 4294967295"` |
393
+ | `z.nan()` | `"number.NaN"` |
394
+ | `z.bigint().min(5n)` | `"bigint"` with a `.narrow()` |
395
+ | `z.file()`, with `.max(n)` or `.mime(type)` | `"File"`, with a `.narrow()` on its `size` and `type` |
396
+ | `z.promise(T)`, `z.function()` | `"Promise"`, `"Function"` |
397
+ | `z.xor([A, B])` | a `.pipe()` that calls both and rejects unless one passes |
398
+ | `.prefault(x)` | `.default(x)`, which is an input as `.prefault()`'s is |
399
+ | `.overwrite(fn)` | `.pipe(fn)` |
400
+ | `.nonoptional()` | the key without its `?` |
401
+ | `.unwrap()` on a nullable or optional schema | `T.exclude("null")`, `T.exclude("undefined")` |
402
+ | `T.element` on an array, `T.valueType` on a record | keep that Type in a `const`: `T.get(0)` and `T.get("key")` add `undefined` to it |
403
+ | `.isOptional()`, `.isNullable()` | `T.allows(undefined)`, `T.allows(null)` |
404
+ | `T.options`, `T.enum.a` on a `z.enum` | `T.select("unit").map(u => u.unit)`, or keep the values in an `as const` array of your own |
405
+ | `schema instanceof z.ZodObject` | `T.extends("object")` |
406
+ | `.meta({ title, examples })`, a registry | `.configure({ title, examples })`, read back from `T.meta` |
407
+ | `z.config(z.locales.de())` | `configure({ locale: de })`, see [i18n](https://arktype.io/docs/i18n); only `en` and `de` ship |
408
+ | `zfd.formData({ ... })` from `zod-form-data` | `type("FormData.parse").to({ ... })`, see [Form data](#form-data) |
409
+ | `z.fromJSONSchema(schema)` | `jsonSchemaToType(schema)` from [`@ark/json-schema`](https://arktype.io/docs/json-schema/from-json-schema) |
192
410
 
193
411
  ## Defaults that differ
194
412
 
@@ -202,11 +420,28 @@ Zod Mini spells most methods as functions, so `z.optional(z.string())` maps like
202
420
  | `number` accepts `NaN` | no | no | no | no | no | no | yes |
203
421
  | An array where an object is expected | accepted | rejected | accepted | rejected | rejected | rejected | rejected |
204
422
  | Empty string for a plain string | accepted | accepted | accepted | accepted | rejected if required | rejected | accepted |
423
+ | Arrays and objects in the output are copies | only if changed | yes | yes | returns a boolean | only if changed | yes | yes |
424
+
425
+ Two global options cover the first three rows, set with `configure` from `arktype/config` in a file imported before anything creates a Type:
426
+
427
+ ```ts
428
+ import { configure } from "arktype/config"
429
+
430
+ configure({
431
+ // remove undeclared keys, as Zod, Valibot and Effect do
432
+ onUndeclaredKey: "delete",
433
+ // accept undefined at an optional key and replace it with a key's default,
434
+ // as Zod, Valibot, Yup, Joi and Effect do
435
+ exactOptionalPropertyTypes: false
436
+ })
437
+ ```
438
+
439
+ Set `exactOptionalPropertyTypes: false` only if your `tsconfig.json` doesn't turn TypeScript's option of that name on: with it on, the types ArkType infers leave out the `undefined` its optional keys would accept.
205
440
 
206
- What to write when the old behavior matters:
441
+ To change one Type instead:
207
442
 
208
443
  ```ts
209
- // remove undeclared keys like Zod, Valibot and Effect, for this object only
444
+ // remove undeclared keys, for this object only
210
445
  const Stripped = type({ "+": "delete", name: "string" })
211
446
 
212
447
  // reject them like Joi or Zod's .strict()
@@ -228,39 +463,39 @@ const Measurement = type(
228
463
  )
229
464
 
230
465
  // reject an array, which matches an object whose keys are all optional
466
+ // (and comes back with its elements deleted, as undeclared keys), or a
467
+ // Record whose values its elements are
231
468
  const Filters = type({ "limit?": "number", "cursor?": "string" }).narrow(
232
- (o, ctx) => !Array.isArray(o) || ctx.reject("an object")
469
+ (o, ctx) => !Array.isArray(o) || ctx.mustBe("an object")
233
470
  )
234
471
 
235
472
  // count a string's length in code points, like Zod 4.5's .min(1).max(32)
236
473
  const Title = type("string").narrow((s, ctx) => {
237
474
  const length = [...s].length
238
- return (length >= 1 && length <= 32) || ctx.reject("1 to 32 characters")
475
+ return (length >= 1 && length <= 32) || ctx.mustBe("1 to 32 characters")
239
476
  })
240
477
  ```
241
478
 
242
- `"+"` 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`.
243
-
244
- 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:
245
-
246
- ```ts
247
- // z.union([z.object({ uri, text }), z.object({ uri, blob })])
248
- const Contents = type({ "+": "ignore", uri: "string", text: "string" })
249
- .or({ "+": "ignore", uri: "string", blob: "string" })
250
- .to({ "+": "delete", uri: "string", "text?": "string", "blob?": "string" })
251
- ```
479
+ `"+"` applies to its own object, not to nested ones, and `.merge()` takes it from the object merged in, so repeat it there. The global option covers every object.
252
480
 
253
481
  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()`.
254
482
 
483
+ A Type's output shares what it didn't change with its input. An object that deletes undeclared keys is a new one, but an array of strings, a `Map`, a `Set` or a `"+": "ignore"` object is the caller's own, where Zod returned a copy. Code that sorts or pushes to a parsed array now changes the input too, so copy it first, as in `[...out.tags].sort()`.
484
+
255
485
  ## Semantics to check
256
486
 
257
- **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.
487
+ ### Transforms run in order
488
+
489
+ `.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.
258
490
 
259
491
  ```ts
260
- // Zod: z.string().transform(s => s.length).refine(n => n > 2)
492
+ // Zod: z.string().transform(s => s.length).refine(n => n > 2, "Too short")
261
493
  const Length = type("string")
262
494
  .pipe(s => s.length)
263
- .narrow(n => n > 2)
495
+ .narrow((n, ctx) => n > 2 || ctx.reject({ message: "Too short" }))
496
+
497
+ // Zod: z.string().trim().toLowerCase().email()
498
+ const Email = type("string.trim").to("string.lower").to("string.email")
264
499
 
265
500
  // Zod: z.preprocess(v => (typeof v === "string" ? v.split(",") : v), z.array(z.string()))
266
501
  const Tags = type("string | string[]")
@@ -268,7 +503,9 @@ const Tags = type("string | string[]")
268
503
  .to("string[]")
269
504
  ```
270
505
 
271
- **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()`:
506
+ ### Coercion is a parse
507
+
508
+ 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()`:
272
509
 
273
510
  ```ts
274
511
  // z.coerce.number(), which is Number(value) for any input
@@ -276,7 +513,11 @@ const Count = type("unknown").pipe(Number).to("number")
276
513
 
277
514
  // z.coerce.number().int().positive().default(8080) in an object
278
515
  const Server = type({
279
- port: type("unknown").pipe(Number).to("number.integer > 0").default(8080)
516
+ port: type("unknown")
517
+ // the default covers a missing key, and this one that's undefined
518
+ .pipe(v => Number(v === undefined ? 8080 : v))
519
+ .to("number.integer > 0")
520
+ .default(8080)
280
521
  })
281
522
 
282
523
  // z.coerce.date(), which is new Date(value) for any input, so null is 1970-01-01
@@ -289,22 +530,173 @@ const When = type("unknown")
289
530
  // stricter, for strings only: rejects " 1", "0x10" and ""
290
531
  const Page = type("string.numeric.parse")
291
532
 
292
- // z.stringbool() accepts "true", "1", "yes", "on" and their opposites; write the set you need
533
+ // z.stringbool() accepts "true", "1", "yes", "on", "y" and "enabled", their
534
+ // opposites, and any casing of them; write the set you need
293
535
  const Flag = type("'true' | 'false'").pipe(s => s === "true")
294
536
  ```
295
537
 
296
- **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`:
538
+ - A default is an input, so a transform's default is what it parses, as Zod's `.prefault()` is: `z.stringbool().default(false)` is `Flag.default("false")`.
539
+ - `unknown` includes `undefined`, so a coercion at an optional or defaulted key is handed a key that's present as `undefined`, as `process.env`'s may be, where Zod's `.optional()` and `.default()` answer first. Return it or the default from the pipe, as `Server` does: `z.coerce.number().optional()` is `"limit?": type("unknown").pipe(v => (v === undefined ? v : Number(v))).to("number | undefined")`.
540
+
541
+ ### Form data
542
+
543
+ `schema.safeParse(Object.fromEntries(formData))` stays `T(Object.fromEntries(formData))`. `type("FormData.parse")` takes the `FormData` itself and keeps a repeated key's values as an array, so it replaces `zod-form-data`:
297
544
 
298
545
  ```ts
299
- // Zod: .superRefine((d, ctx) => ctx.addIssue({ code: "custom", message: "...", path: ["end"] }))
546
+ // zfd.formData({ name: zfd.text(), age: zfd.numeric(), agree: zfd.checkbox(), tags: zfd.repeatable() })
547
+ const Signup = type("FormData.parse").to({
548
+ // zfd.text(): an empty field is rejected
549
+ name: "string > 0",
550
+ // zfd.numeric(), without the padded strings like " 7 " that Number() reads
551
+ age: "string.numeric.parse",
552
+ // zfd.checkbox(): "on" when checked, missing when not
553
+ agree: type("'on' | undefined")
554
+ .pipe(v => v === "on")
555
+ .default(undefined),
556
+ // zfd.repeatable(): one value arrives as a string, none as a missing key
557
+ tags: type("string | string[] | undefined")
558
+ .pipe(v =>
559
+ v === undefined ? []
560
+ : typeof v === "string" ? [v]
561
+ : v
562
+ )
563
+ .default(undefined)
564
+ })
565
+ ```
566
+
567
+ ### Refinements
568
+
569
+ A `.narrow()` returns `true`, or `ctx.reject()` with the `message` Zod's held. Its `relativePath` is Zod's `path`, from the value being narrowed. Don't pass that as `path`, which is from the root of the data, so it's wrong once the object is nested or in an array:
570
+
571
+ ```ts
572
+ // Zod: .refine(d => d.start <= d.end, { message: "End must not be before start", path: ["end"] })
300
573
  const Range = type({ start: "number", end: "number" }).narrow(
301
574
  (d, ctx) =>
302
575
  d.start <= d.end ||
303
- ctx.reject({ message: "end must not be before start", path: ["end"] })
576
+ ctx.reject({
577
+ message: "End must not be before start",
578
+ relativePath: ["end"]
579
+ })
304
580
  )
305
581
  ```
306
582
 
307
- **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:
583
+ To report several errors, as a `.superRefine()` calling `ctx.addIssue()` more than once does, call `ctx.error()` for each, then return `true`:
584
+
585
+ ```ts
586
+ const Order = type({ quantity: "number", price: "number" }).narrow((d, ctx) => {
587
+ if (d.quantity < 1)
588
+ ctx.error({ message: "Order at least one", relativePath: ["quantity"] })
589
+ if (d.price < 0)
590
+ ctx.error({ message: "Price can't be negative", relativePath: ["price"] })
591
+ return true
592
+ })
593
+ ```
594
+
595
+ - A narrow that returns `false` without `ctx.reject()` says `must be valid according to an anonymous predicate`, so always reject with text.
596
+ - A narrow on an object runs only once every key is valid. Zod 4 runs a `.refine()` even when a key fails a check like `.min()`, though not when one is missing or of the wrong type, so its issue could join theirs.
597
+ - A narrow never rejects a literal with its own text. ArkType calls it on each literal the Type allows, like `true`, `false`, `null`, `undefined` or `'a'`, when the Type is defined, and removes those it rejects, so `z.boolean().refine(v => v, "Accept the terms")` written as a narrow says `must be true`. Write the values the Type allows, with the message: `["true", "@", { message: "Accept the terms" }]`, which also infers `true` where Zod inferred `boolean`.
598
+
599
+ ### Custom messages
600
+
601
+ A custom Zod message becomes a `message`: one whole sentence, shown as you wrote it. An issue's `message` holds it without its path, as Zod's `issue.message` did, and `summary` and a thrown `TraversalError` write the path and a colon before it:
602
+
603
+ ```ts
604
+ // Zod: z.object({ name: z.string().min(1, "Name is required") })
605
+ const Named = type({
606
+ // or type("string >= 1").configure({ message: "Name is required" })
607
+ name: ["string >= 1", "@", { message: "Name is required" }]
608
+ })
609
+
610
+ const out = Named({ name: "" })
611
+
612
+ if (out instanceof type.errors) {
613
+ // "Name is required", as Zod's issue.message was
614
+ out.issues[0].message
615
+ // "name: Name is required"
616
+ out.summary
617
+ }
618
+ ```
619
+
620
+ A library reading the Type through [Standard Schema](https://arktype.io/docs/standard-schema), like TanStack Form, react-hook-form's `standardSchemaResolver` or tRPC, gets the same `message` on each issue, beside its `path`.
621
+
622
+ - **Only `message` takes a sentence.** `ctx.reject("a valid zip code")`, `ctx.mustBe("a valid zip code")`, `.describe("a valid zip code")`, `expected` and a string after `"@"` each take what the value must be, so they read `must be a valid zip code`. A Zod message passed to one reads `must be Enter a valid zip code`.
623
+ - **It covers the whole value.** A string `message` is written for any value the Type rejects, of the wrong type included, and for a key that's absent: `Named({})` also says `Name is required`. Configure the key's whole value, last, after any `.pipe()` or `.to()`.
624
+ - **With `| null` or `| undefined`, configure the union.** `["string.email | null", "@", { message }]` says the message for any value it rejects. A message on one branch, as in `Email.configure({ message }).or("null")`, is lost for a value of the wrong type, which reads `must be a string or null`. With `exactOptionalPropertyTypes: false`, an optional or defaulted key's value is such a union, so where the message must cover the wrong type too, as a Zod `z.string({ error })` does, write `undefined` into it: `"email?": ["string.email | undefined", "@", { message }]`. Always write a boolean's, a literal's or an enum's message on the union, as in `"role?": ["'admin' | 'user' | undefined", "@", { message }]`: a wrong value is their only error, so a message on `Role` alone is never said beside `null` or `undefined`.
625
+ - **A parse keyword's own failure keeps its text.** A `message` on `string.date.parse`, `string.url.parse` or `string.json.parse` is said for a value that isn't a string, but a string that doesn't parse still reads `must be a parsable date`. Check the string, then convert it: `type("string.date").pipe(s => new Date(s)).configure({ message })`, or `"string.url"` with `new URL(s)`. For JSON, call `JSON.parse` in a `.pipe()` and report its failure with `ctx.error({ message })`.
626
+ - **For a message per check, name the check.** A second argument to `.configure()`, or a fourth element of the `"@"` tuple, is the [code](https://arktype.io/docs/errors#error-codes) of the errors the message is for, like `minLength`, `pattern`, `min` or `divisor`:
627
+
628
+ ```ts
629
+ // Zod: z.string().min(8, "Use 8 or more characters").regex(/[0-9]/, "Include a number")
630
+ const Password = type("string >= 8 & /[0-9]/")
631
+ .configure({ message: "Use 8 or more characters" }, "minLength")
632
+ .configure({ message: "Include a number" }, "pattern")
633
+
634
+ const Account = type({
635
+ // only an empty name says it, as in Zod
636
+ name: ["string >= 1", "@", { message: "Name is required" }, "minLength"],
637
+ password: Password
638
+ })
639
+ ```
640
+
641
+ A value of the wrong type, or a missing key, then says ArkType's own text, like `must be a string`, as it said Zod's. To give those their own messages, as Zod 3's `required_error` and `invalid_type_error` do, name `"self"` for a missing key and `"domain"` for a value of the wrong type:
642
+
643
+ ```ts
644
+ // Zod 3: z.string({ required_error: "SKU is required", invalid_type_error: "SKU must be text" })
645
+ // .regex(/^[A-Z]{3}-\d{4}$/, "SKU looks like ABC-1234")
646
+ const Sku = type(/^[A-Z]{3}-\d{4}$/)
647
+ .configure({ message: "SKU is required" }, "self")
648
+ .configure({ message: "SKU must be text" }, "domain")
649
+ .configure({ message: "SKU looks like ABC-1234" }, "pattern")
650
+ ```
651
+
652
+ - Zod says `required_error` for a key given `undefined` too, which here is a value of the wrong type. To keep that, write `"domain"`'s message as `error => (error.data === undefined ? "SKU is required" : "SKU must be text")`.
653
+ - A code names every check of that kind in the Type, a nested key's included, so configure a key's value rather than the object around it.
654
+ - A `message` configured without a code replaces those configured before it, so configure the whole value first and its checks after.
655
+ - Two checks with one code share its message, like two patterns, or an array's length and its elements', which are both `minLength`. Configure each as its own Type and intersect them: `HasDigit.and(HasCapital)`, or `Tags` below.
656
+ - A function, like Zod 4's `error: issue => ...`, receives the error: `error.data` is Zod's `issue.input`, and once `error.code === "min"` is checked, `error.rule` is its `issue.minimum`. A missing key doesn't say a function's message, so give `"self"` a string.
657
+ - After a `.pipe()` or `.to()`, a code doesn't reach the Type the output is checked with, so configure that Type before passing it to `.to()`. A message for the whole value, or for `"self"`, on the transformed Type replaces the ones inside it, so use one there only where a single message is enough.
658
+
659
+ When several checks fail at once, ArkType reports a pattern before a length, whichever was written first, where Zod reports them as written. A form that shows the first message for a field would then say `Enter a valid email` for an empty one, or `Include a number` for a password that's too short. To keep what the form said first:
660
+
661
+ - A format already rejects an empty string, so leave out the `.min(1)` and choose the text from the value, as `Email` does.
662
+ - Where a length comes before a pattern, write the pattern as a `.narrow()`, which runs once the length passes, as `Password` does.
663
+
664
+ ```ts
665
+ // Zod: z.string().min(1, "Email is required").email("Enter a valid email")
666
+ const Email = type("string.email").configure(
667
+ {
668
+ message: error =>
669
+ error.data === "" ? "Email is required" : "Enter a valid email"
670
+ },
671
+ "pattern"
672
+ )
673
+
674
+ // Zod: z.string().min(8, "Use 8 or more characters").regex(/[0-9]/, "Include a number")
675
+ const Password = type("string >= 8")
676
+ .configure({ message: "Use 8 or more characters" }, "minLength")
677
+ .narrow(
678
+ (s, ctx) => /[0-9]/.test(s) || ctx.reject({ message: "Include a number" })
679
+ )
680
+
681
+ // Zod: z.string().trim().min(1, "Name is required").max(50, "Name is too long")
682
+ const Name = type("string.trim").to(
683
+ type("0 < string <= 50")
684
+ .configure({ message: "Name is required" }, "minLength")
685
+ .configure({ message: "Name is too long" }, "maxLength")
686
+ )
687
+
688
+ // Zod: z.array(z.string().min(1, "Tag can't be empty")).min(1, "Add at least one tag")
689
+ const Tag = type("string >= 1").configure({ message: "Tag can't be empty" })
690
+ const Tags = type("unknown[] >= 1")
691
+ .configure({ message: "Add at least one tag" }, "minLength")
692
+ .and(Tag.array())
693
+ ```
694
+
695
+ Through react-hook-form's resolvers, these four show the same message for each field as their Zod originals.
696
+
697
+ ### Fallbacks
698
+
699
+ 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:
308
700
 
309
701
  ```ts
310
702
  const Count = type("number")
@@ -320,33 +712,276 @@ const Settings = type({
320
712
  })
321
713
  ```
322
714
 
323
- **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.
715
+ The key's input type is `unknown`, where `z.input` gave the inner schema's.
716
+
717
+ ### Unions of objects
718
+
719
+ ArkType finds a union's 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.
720
+
721
+ An object transforms its input when it deletes undeclared keys, by `"+": "delete"` or the global option, or when one of its keys has a default or a transform. A union can't hold a transform whose input another branch also accepts: it throws a `ParseError` saying the union is indeterminate, since such data could come out as either. Objects a literal key tells apart, like `kind: "'card'"` and `kind: "'bank'"`, never overlap. These do:
722
+
723
+ - two objects with no such key, like `{ uri, text }` and `{ uri, blob }`
724
+ - an object beside an array, a `Date` or another class's instance, which could hold the object's keys, as in `Item.or(Item.array())`
725
+ - a `Record` beside an array
726
+
727
+ For those, choose the branch in a `.pipe()`, which infers the union of what they return:
728
+
729
+ ```ts
730
+ const Item = type({ "+": "delete", id: "string" })
731
+ const Items = Item.array()
732
+
733
+ // z.union([Item, z.array(Item)])
734
+ const OneOrMany = type("object").pipe(v =>
735
+ Array.isArray(v) ? Items(v) : Item(v)
736
+ )
737
+
738
+ const Text = type({ "+": "delete", uri: "string", text: "string" })
739
+ const Blob = type({ "+": "delete", uri: "string", blob: "string" })
740
+
741
+ // z.union([Text, Blob]), which takes the first branch that matches
742
+ const Contents = type("object").pipe(v => {
743
+ const text = Text(v)
744
+ return text instanceof type.errors ? Blob(v) : text
745
+ })
746
+ ```
747
+
748
+ The errors are those of the branch the pipe ran, at the union's path.
749
+
750
+ Where objects delete undeclared keys, a `.narrow()` or `.pipe()` on a union of them reports differently once `null` or `undefined` joins it, as `.or("null")` or an optional key does. Its errors become one `union` issue at the union's path, like `radius must be a number or must be undefined`, which has neither the failing key's path nor a message from a branch's own `.narrow()`. Refine from the object that holds the key instead:
751
+
752
+ ```ts
753
+ const Shape = type({ kind: "'circle'", radius: "number" }).or({
754
+ kind: "'square'",
755
+ side: "number"
756
+ })
757
+
758
+ const fits = (shape: typeof Shape.infer) =>
759
+ shape.kind === "circle" ? shape.radius <= 10 : shape.side <= 20
760
+
761
+ // Zod: z.object({ shape: Shape.refine(fits, "Too big").optional() })
762
+ const Drawing = type({ "shape?": Shape }).narrow(
763
+ (drawing, ctx) =>
764
+ drawing.shape === undefined ||
765
+ fits(drawing.shape) ||
766
+ ctx.reject({ message: "Too big", relativePath: ["shape"] })
767
+ )
768
+ ```
769
+
770
+ ### Recursion needs no annotation
324
771
 
325
- **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:
772
+ Replace `z.lazy`, a Zod 4 getter, `v.lazy`, `Type.Recursive`, `yup.lazy`, `Joi.link` and `Schema.suspend` with `this`, for a type that refers to itself, or a scope, for types that refer to each other:
326
773
 
327
774
  ```ts
328
775
  const Category = type({ name: "string", subcategories: "this[]" })
329
776
 
330
777
  const types = scope({
331
- Json: "string | number | boolean | null | Json[] | JsonObject",
332
- JsonObject: { "[string]": "Json" },
333
- Filter: { "[string]": "Json | Filter" }
778
+ User: { name: "string", "posts?": "Post[]" },
779
+ Post: { title: "string", author: "User" }
334
780
  }).export()
335
781
  ```
336
782
 
337
- Delete the hand-written TypeScript type that `z.lazy` needed; `typeof types.Filter.infer` replaces it.
783
+ Inside a scope, `type()` can't see the scope's names, so write a refinement or a transform there as a tuple: `["Post[]", ":", (posts, ctx) => ...]` for a `.narrow()`, `["string", "=>", s => s.trim()]` for a `.pipe()`.
784
+
785
+ Delete the hand-written TypeScript type that `z.lazy` needed; `typeof Category.infer` and `typeof types.Post.infer` replace it. Where the module's declarations are emitted, as for a published package or a TypeScript project reference, `tsc` can't write the cycle in a `.d.ts`, so emit them with [`arktype-precompile --declare`](https://arktype.io/docs/precompile/advanced#cyclic-types), or keep the type and [declare the Type with it](https://arktype.io/docs/scopes#cyclic-types), `type.declare<Category>().type({ ... })`. For JSON data, use the `object.json` keyword rather than a recursive type of your own: `z.json()` is `"string | number | boolean | null | object.json"`.
786
+
787
+ ### Composing objects
788
+
789
+ `.merge()` replaces keys like Zod's `.extend()` or `v.object({ ...a.entries })`. `.and()` intersects, like `Type.Composite`, and throws when a key's types conflict. `.pick()` and `.omit()` take key names, as in `.pick("name", "email")`. Like Zod's, they and `.partial()` keep an object's `"+"`, so a `.strict()` object's are strict too, where `.merge()` takes `"+"` from the object merged in.
790
+
791
+ A `.narrow()` on an object doesn't survive them. `.merge()`, a `"..."` spread, `.pick()`, `.omit()` and `.partial()` take the object's keys and leave its narrow behind, so a refinement Zod's `.extend()` kept no longer runs. Where the object also deletes undeclared keys, they throw instead: `merge operand must be an object (was (In: { ... }) => To<...>)`. Either way, keep the keys in a Type of their own, derive from that, and add the narrow last:
792
+
793
+ ```ts
794
+ import { type, type Traversal } from "arktype"
795
+
796
+ const passwordsMatch = (
797
+ d: { password: string; confirm: string },
798
+ ctx: Traversal
799
+ ) =>
800
+ d.password === d.confirm ||
801
+ ctx.reject({ message: "Passwords must match", relativePath: ["confirm"] })
802
+
803
+ const Credentials = type({ password: "string >= 8", confirm: "string" })
804
+
805
+ const Signup = Credentials.narrow(passwordsMatch)
806
+
807
+ // Zod: Signup.extend({ email: z.email() }), which keeps Signup's refinement
808
+ const Invite = Credentials.merge({ email: "string.email" }).narrow(
809
+ passwordsMatch
810
+ )
811
+ ```
812
+
813
+ ### Schema factories
814
+
815
+ A function that builds a schema from another becomes a [generic](https://arktype.io/docs/generics). Where it called `.omit()`, `.pick()`, `.partial()`, `.required()` or `.extend()` on its parameter, the generic's body uses `Omit`, `Pick`, `Partial`, `Required` or `Merge`, since the `Type<t>` a TypeScript function is passed has no object methods until `t` is known:
816
+
817
+ ```ts
818
+ // Zod: const page = <T extends z.ZodType>(item: T) =>
819
+ // z.object({ items: z.array(item), total: z.number() })
820
+ const Page = type("<t>", { items: "t[]", total: "number" })
821
+
822
+ // Zod: const crud = <T extends z.ZodObject>(S: T) =>
823
+ // ({ create: S.omit({ id: true }), update: S.partial().required({ id: true }) })
824
+ const Create = type("<t extends object>", "Omit<t, 'id'>")
825
+ const Update = type(
826
+ "<t extends object>",
827
+ "Merge<Partial<Omit<t, 'id'>>, Pick<t, 'id'>>"
828
+ )
829
+
830
+ const Task = type({
831
+ id: "string.uuid",
832
+ title: "string",
833
+ done: "boolean = false"
834
+ })
835
+
836
+ const TaskPage = Page(Task)
837
+ const TaskCreate = Create(Task)
838
+ const TaskUpdate = Update(Task)
839
+
840
+ // { id: string; title?: string; done?: boolean }
841
+ type TaskUpdate = typeof TaskUpdate.infer
842
+ ```
843
+
844
+ A function that reads an object schema's keys, as one iterating `schema.shape` did, takes `Type<Record<string, unknown>>` and reads its `props`, each with its `key`, whether it's `required` or `optional` as its `kind`, and its Type as `value`.
845
+
846
+ ### Records with literal keys
847
+
848
+ Write `z.record(z.enum(["a", "b"]), T)` as named keys, with `"+": "reject"`, since Zod rejects a key outside the enum rather than removing it: `{ "+": "reject", a: T, b: T }`. Add `?` to each key for `z.partialRecord`, and for Zod 3, whose enum-keyed records are partial.
338
849
 
339
- **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.
850
+ Where the keys are in an array, or the shape is built at runtime as `z.object(Object.fromEntries(...))` built it, build the definition the same way and pass it to `type.raw`, which takes any definition and infers nothing, then give it its type: `type.raw(Object.fromEntries(FLAGS.map(flag => [flag, "boolean"]))).as<Record<Flag, boolean>>()`. `type()` infers `unknown` from an object built that way and rejects a `string` variable.
340
851
 
341
- **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" })`.
852
+ 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" })`.
342
853
 
343
- **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`.
854
+ ### Brands
344
855
 
345
- **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 })`.
856
+ `.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`.
346
857
 
347
- **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.
858
+ ### Errors are values
859
+
860
+ `T(data)` returns the data or an `ArkErrors`, and `T.assert(data)` throws a `TraversalError`. To change what an error says, `.describe("a strong password")` gives `must be a strong password`, and `.configure({ message: "Choose a stronger password" })` replaces that sentence; see [Custom messages](#custom-messages).
861
+
862
+ ### Descriptions
863
+
864
+ Zod's and Valibot's `description` only documents. `z.toJSONSchema` writes it as `description`, which is how a model reads what a tool's parameter or a field of structured output means, and what an OpenAPI document shows. ArkType's `.describe(text)` writes the same `description`, so keep it wherever a model or an OpenAPI generator reads the schema. It's also what errors say the value must be:
865
+
866
+ ```ts
867
+ // Zod: z.object({ limit: z.number().min(1).max(50).describe("Maximum number of results") })
868
+ const Search = type({
869
+ limit: type("1 <= number <= 50").describe("Maximum number of results")
870
+ })
348
871
 
349
- **Synchronous only.** ArkType doesn't await. Move an async `refine`, Yup `test` or Joi `external` out of the schema and run it after validation.
872
+ // limit: { type: "number", description: "Maximum number of results", maximum: 50, minimum: 1 }
873
+ Search.toJsonSchema()
874
+
875
+ // limit must be Maximum number of results
876
+ const out = Search({ limit: 99 })
877
+ ```
878
+
879
+ To keep each check's own error, like `limit must be at most 50`, describe the value alone: `.describe(text, "self")`. Use it in a tool's `inputSchema`, on a value with checks or keys of its own, like a range, a format, an array or an object. With [the two options above](#zod-side-by-side), a description on `"self"` is left out of `.in`, `.out` and output schemas, like an MCP tool's `outputSchema`, and of an optional or defaulted union of literals.
880
+
881
+ Where nothing reads the JSON Schema, keep the text in a comment, or in `.configure({ title: text })`, which errors don't say and JSON Schema writes as `title`.
882
+
883
+ A string `message` or `expected` configured on a whole value is written into the JSON Schema too, as a keyword of that name, so a model provider is sent it and a strict validator like Ajv rejects the schema. A message for one check, like `.configure({ message }, "minLength")`, isn't written, and neither is a function.
884
+
885
+ ### OpenAPI documents
886
+
887
+ The registry of `@asteasolutions/zod-to-openapi` becomes a `components` object you write, a `$ref` wherever a registered schema was used, and a parameter for each key of a `query` or `params` object:
888
+
889
+ ```ts
890
+ import { type, type JsonSchema, type ToJsonSchema } from "arktype"
891
+
892
+ const openapi: ToJsonSchema.Options = {
893
+ target: "openapi-3.0",
894
+ fallback: {
895
+ // a transformed value, like a coerced query parameter, as what it becomes
896
+ morph: (ctx: ToJsonSchema.MorphContext) => ctx.out ?? ctx.base
897
+ }
898
+ }
899
+
900
+ // registry.register("User", User)
901
+ const User = type({ id: "string.uuid", name: "string" })
902
+ const UserRef = User.configure({
903
+ jsonSchema: { $ref: "#/components/schemas/User" }
904
+ })
905
+
906
+ // items: { $ref: "#/components/schemas/User" }
907
+ const UserPage = type({ items: UserRef.array(), total: "number" })
908
+
909
+ const components = {
910
+ User: User.toJsonSchema(openapi),
911
+ UserPage: UserPage.toJsonSchema(openapi)
912
+ }
913
+
914
+ const isObject = (s: JsonSchema): s is JsonSchema.Object => s.type === "object"
915
+
916
+ // request: { query: ListQuery } is parameters(ListQuery.toJsonSchema(openapi), "query")
917
+ const parameters = (object: JsonSchema, where: "query" | "path") => {
918
+ if (!isObject(object)) return []
919
+ return Object.entries(object.properties ?? {}).map(([name, property]) => ({
920
+ name,
921
+ in: where,
922
+ required: object.required?.includes(name) ?? false,
923
+ schema: property
924
+ }))
925
+ }
926
+ ```
927
+
928
+ With `onUndeclaredKey: "delete"`, each object's schema says `additionalProperties: false`, which zod-to-openapi left out, and `.in` and `.out` write a registered schema in full where `toJsonSchema()` writes its `$ref`.
929
+
930
+ Call `toJsonSchema(openapi)` on each Type by name, as above, rather than in a function that takes any Type. A [precompiled](https://arktype.io/docs/precompile) build can't tell which Types such a function converts, and where objects delete undeclared keys, its call throws for a Type holding a `$ref`.
931
+
932
+ `hono-openapi` takes `UserRef` the same way, in `resolver(UserRef)` and `validator("json", UserRef)`. Name each schema in the document it builds: `openAPIRouteHandler(app, { documentation: { components: { schemas: { User: (await resolver(User).toOpenAPISchema()).schema } } } })`. It converts each Type itself, so a coerced key, whose input is `unknown`, is written without a type there until it's given a schema, before its `.default()`: `.configure({ jsonSchema: { type: "integer", minimum: 1, maximum: 100 } })`.
933
+
934
+ ### Dates and formats
935
+
936
+ `z.iso.datetime()` and `z.string().datetime()` require a `Z` and, from Zod 4.5, seconds, and `z.iso.date()` a date alone. `string.date.iso` accepts all of those, and offsets and date-times without one, so intersect a pattern to keep rejecting them:
937
+
938
+ ```ts
939
+ // z.iso.datetime()
940
+ const Instant = type("string.date.iso").and(/T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/)
941
+
942
+ // z.iso.datetime({ offset: true })
943
+ const Zoned = type("string.date.iso").and(
944
+ /T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/
945
+ )
946
+
947
+ // z.iso.date()
948
+ const Day = type("string.date.iso").and(/^\d{4}-\d{2}-\d{2}$/)
949
+ ```
950
+
951
+ Zod 3, and Zod 4 before 4.5, also take `2025-01-01T10:00Z`, so write the seconds as optional there: `/T\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z$/`.
952
+
953
+ Valibot's `v.isoDate()` is `Day` and `v.isoTimestamp()` is `Zoned`. Its `v.isoDateTime()` takes only minutes and no offset, like `2025-01-01T10:00`, so its pattern is `/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/`.
954
+
955
+ `string.date.iso` checks the format, not the calendar, so `2020-02-30` passes, where Zod and `string.date.iso.parse` reject it.
956
+
957
+ JSON Schema has one `pattern` for a string, so `toJsonSchema()` throws for these, and the schema a tool reads through Standard Schema keeps only the second. Where one is converted, say what to write, as Zod does: `Instant.configure({ jsonSchema: { type: "string", format: "date-time" } })`, or `format: "date"` for `Day`.
958
+
959
+ In JSON Schema, `format` is an annotation and validates nothing unless the validator, like ajv with `ajv-formats`, checks it; `string.email` always validates.
960
+
961
+ ### Synchronous only
962
+
963
+ ArkType doesn't await, so there's no `parseAsync`. An async `.narrow()` is a type error. An async `.pipe()` type-checks, but its promise is the output: validation has passed by the time it settles, so an error it reports after an `await` is lost. Move an async `refine` or `transform`, Yup `test` or Joi `external` out of the schema, run it on the validated data, and report its failure in the shape the caller reads:
964
+
965
+ ```ts
966
+ import { type, flatMessagesByPath } from "arktype"
967
+
968
+ const isTaken = async (name: string) => name === "admin"
969
+
970
+ // Zod: username: z.string().min(3)
971
+ // .refine(async name => !(await isTaken(name)), "Username is taken")
972
+ const Signup = type({ username: "string >= 3", email: "string.email" })
973
+
974
+ const signup = async (data: unknown) => {
975
+ const out = Signup(data)
976
+ if (out instanceof type.errors)
977
+ return { ok: false as const, errors: flatMessagesByPath(out) }
978
+ if (await isTaken(out.username))
979
+ return { ok: false as const, errors: { username: ["Username is taken"] } }
980
+ return { ok: true as const, data: out }
981
+ }
982
+ ```
983
+
984
+ Zod runs an async check beside the other keys' checks, so it reports a taken username along with an invalid email. This reports the email alone, then the username once the rest is valid.
350
985
 
351
986
  ## How to convert
352
987
 
@@ -386,6 +1021,8 @@ const User = type({ name: "string", address: Address })
386
1021
 
387
1022
  A Valibot schema embeds the same way. Yup's validates asynchronously, so it can't.
388
1023
 
1024
+ An embedded schema validates, but ArkType [can't see inside it](https://arktype.io/docs/standard-schema#other-validators-in-a-definition): the JSON Schema a tool or an OpenAPI generator reads from the Type is `{}` at that key, and `toJsonSchema()` throws there. Convert a schema those read all at once.
1025
+
389
1026
  ## Precompile
390
1027
 
391
1028
  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.
@@ -407,58 +1044,80 @@ To see what's left, run `npx arktype-precompile --check`, which lists each defin
407
1044
 
408
1045
  ## Valibot
409
1046
 
410
- | Valibot | ArkType |
411
- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
412
- | `v.object`, `v.looseObject`, `v.strictObject` | `"+": "delete"`, the default, `"+": "reject"` |
413
- | `v.objectWithRest(entries, rest)` | an index signature, `"[string]": ...` |
414
- | `v.optional(T)`, `v.exactOptional(T)` | `"key?": "T \| undefined"`, `"key?": "T"` |
415
- | `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](#defaults-that-differ) |
416
- | `v.nullable(T)`, `v.nullish(T)` | `"T \| null"`, `"key?": "T \| null \| undefined"` |
417
- | `v.picklist(["a", "b"])`, `v.enum(E)` | `"'a' \| 'b'"`, `type.valueOf(E)` |
418
- | `v.union`, `v.variant("type", [...])`, `v.intersect` | `A.or(B)`, `A.or(B)`, `A.and(B)` |
419
- | `v.array`, `v.tuple`, `v.tupleWithRest`, `v.record` | `"T[]"`, `[A, B]`, `[A, "...", "B[]"]`, `"Record<string, T>"` |
420
- | `v.lazy` | a scope or `this` |
421
- | `v.pipe(v.string(), v.email(), v.maxLength(255))` | `"string.email <= 255"` |
422
- | `v.minLength`, `v.maxLength`, `v.length`, `v.nonEmpty` | `"string >= n"`, `"string <= n"`, `"string == n"`, `"string > 0"` |
423
- | `v.minValue`, `v.maxValue`, `v.integer`, `v.multipleOf` | `"number >= n"`, `"number <= n"`, `"number.integer"`, `"number % n"` |
424
- | `v.url`, `v.uuid`, `v.isoDateTime`, `v.regex(r)` | `"string.url"`, `"string.uuid"`, `"string.date.iso"`, `/r/` |
425
- | `v.trim()`, `v.toLowerCase()`, `v.toNumber()`, `v.toDate()` | `"string.trim"`, `"string.lower"`, `"string.numeric.parse"`, `"string.date.parse"` |
426
- | `v.check(fn, msg)`, `v.rawCheck` | `.narrow((x, ctx) => fn(x) \|\| ctx.reject({ message: msg }))` |
427
- | `v.forward(v.partialCheck(...), ["key"])` | `.narrow(...)` with `ctx.reject({ path: ["key"] })` |
428
- | `v.transform(fn)` | `.pipe(fn)` |
429
- | `v.brand("Id")` | `.brand("Id")` |
430
- | `v.instance(C)`, `v.date()`, `v.custom(fn)` | `type.instanceOf(C)`, `"Date"`, `type("unknown").narrow(fn)` |
431
- | `v.fallback(T, x)` | none; handle the `ArkErrors` result |
432
- | `v.InferOutput`, `v.InferInput` | `typeof T.infer`, `typeof T.inferIn` |
433
- | `v.parse(S, x)`, `v.safeParse(S, x)` | `T.assert(x)`, `T(x)` |
1047
+ Valibot's defaults are Zod's: `v.object` removes undeclared keys, and `v.optional` accepts `undefined` and replaces it with its default. Set [the same two options](#zod-side-by-side), which the ArkType column assumes. [Semantics to check](#semantics-to-check) applies too, with Valibot's names for Zod's.
1048
+
1049
+ | Valibot | ArkType |
1050
+ | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
1051
+ | `v.object`, `v.looseObject`, `v.strictObject` | the default once configured, `"+": "ignore"`, `"+": "reject"` |
1052
+ | `v.objectWithRest(entries, rest)` | `"[/^(?!a$\|b$)/]": rest`, `a` and `b` the declared keys |
1053
+ | `v.optional(T)`, `v.optional(T, default)` | `"key?": "T"`, `key: "T = default"` |
1054
+ | `v.exactOptional(T)` | `"key?": "T"`, without `exactOptionalPropertyTypes: false` in the config |
1055
+ | `v.nullable(T)`, `v.nullish(T)` | `"T \| null"`, `"key?": "T \| null"` |
1056
+ | `v.literal("a")`, `v.picklist(["a", "b"])`, `v.enum(E)` | `"'a'"`, `"'a' \| 'b'"`, `type.valueOf(E)` |
1057
+ | `v.partial(S)`, `v.required(S)`, `v.keyof(S)` | `T.partial()`, `T.required()`, `T.keyof()` |
1058
+ | `v.pick(S, ["a"])`, `v.omit(S, ["a"])` | `T.pick("a")`, `T.omit("a")` |
1059
+ | `v.union`, `v.variant("type", [...])`, `v.intersect` | `A.or(B)`, `A.or(B)`, `A.and(B)` |
1060
+ | `v.array`, `v.strictTuple`, `v.tupleWithRest`, `v.record` | `"T[]"`, `[A, B]`, `[A, "...", "B[]"]`, `"Record<string, T>"` |
1061
+ | `v.tuple`, which removes extra elements | `[A, B]`, which rejects them |
1062
+ | `v.lazy` | a scope or `this` |
1063
+ | `v.pipe(v.string(), v.email(), v.maxLength(255))` | `"string.email <= 255"` |
1064
+ | `v.minLength`, `v.maxLength`, `v.length`, `v.nonEmpty` | `"string >= n"`, `"string <= n"`, `"string == n"`, `"string > 0"` |
1065
+ | `v.minValue`, `v.maxValue`, `v.integer`, `v.multipleOf` | `"number >= n"`, `"number <= n"`, `"number.integer"`, `"number % n"` |
1066
+ | `v.url`, `v.uuid`, `v.regex(r)` | `"string.url"`, `"string.uuid"`, `/r/` |
1067
+ | `v.isoDate`, `v.isoDateTime`, `v.isoTimestamp` | `"string.date.iso"` with a pattern for each, see [Dates and formats](#dates-and-formats) |
1068
+ | `v.trim()`, `v.toLowerCase()`, `v.toNumber()`, `v.toDate()` | `"string.trim"`, `"string.lower"`, `"string.numeric.parse"`, `"string.date.parse"` |
1069
+ | `v.string("Message")`, `v.email("Message")`, `v.minLength(8, "Message")` | a `message` for each check, by its code: see [Custom messages](#custom-messages) |
1070
+ | `v.check(fn, msg)`, `v.rawCheck` | `.narrow((x, ctx) => fn(x) \|\| ctx.reject({ message: msg }))` |
1071
+ | `v.forward(v.partialCheck(...), ["key"])` | `.narrow(...)` with `ctx.reject({ message, relativePath: ["key"] })`, which runs only once every key is valid |
1072
+ | `v.transform(fn)` | `.pipe(fn)` |
1073
+ | `v.brand("Id")` | `.brand("Id")` |
1074
+ | `v.description(text)`, `v.title(text)` in a pipe | `.describe(text)` where a model or an OpenAPI document reads it, see [Descriptions](#descriptions); `.configure({ title: text })` |
1075
+ | `v.instance(C)`, `v.date()`, `v.custom(fn)` | `type.instanceOf(C)`, `"Date"`, `type("unknown").narrow(fn)` |
1076
+ | `v.fallback(T, x)` | a `.pipe()` that returns `x` for invalid input, see [Fallbacks](#fallbacks) |
1077
+ | `v.InferOutput`, `v.InferInput`, `v.GenericSchema` | `typeof T.infer`, `typeof T.inferIn`, `type.Any` |
1078
+ | `v.parse(S, x)`, `v.safeParse(S, x)`, `v.is(S, x)` | `T.assert(x)`, `T(x)`, `T.allows(x)` |
1079
+ | `v.isValiError(e)` | `e instanceof TraversalError`, whose `e.arkErrors.issues` holds the issues |
1080
+ | `v.flatten(issues).nested` | group `out.issues` by `issue.path.join(".")` |
1081
+
1082
+ `v.partial()` leaves a key with a default missing, where `.partial()` fills it in: call it on a Type of the keys without their defaults, and `.merge()` the defaults into the full object.
434
1083
 
435
1084
  ## TypeBox
436
1085
 
437
- TypeBox schemas are JSON Schema, so [JSON Schema](#json-schema-and-ajv) also applies.
438
-
439
- | TypeBox | ArkType |
440
- | -------------------------------------------------------------- | ------------------------------------------------------ |
441
- | `Type.Object({...})`, `{ additionalProperties: false }` | `type({...})`, `"+": "reject"` |
442
- | `Type.Optional(T)` | `"key?": "T \| undefined"` |
443
- | `Type.String({ minLength, maxLength, pattern })` | `"1 <= string <= 255"`, `/pattern/` |
444
- | `Type.String({ format: "email" })` | `"string.email"` |
445
- | `Type.Number({ minimum, exclusiveMaximum })`, `Type.Integer()` | `"0 <= number < 10"`, `"number.integer"` |
446
- | `Type.Literal`, `Type.Union`, `Type.Enum(E)` | `"'a'"`, `A.or(B)`, `type.valueOf(E)` |
447
- | `Type.Array(T, { minItems })`, `Type.Tuple` | `"T[] >= 1"`, `[A, B]` |
448
- | `Type.Record(Type.String(), T)` | `"Record<string, T>"` |
449
- | `Type.Intersect`, `Type.Composite` | `A.and(B)`, `A.merge(B)` |
450
- | `Type.Partial`, `Type.Pick`, `Type.Omit`, `Type.KeyOf` | `.partial()`, `.pick()`, `.omit()`, `.keyof()` |
451
- | `Type.Recursive(This => ...)` | `this` or a scope |
452
- | `Type.Date()`, `Type.Unknown()`, `Type.Any()` | `"Date"`, `"unknown"`, `"unknown.any"` |
453
- | `Type.Transform(T).Decode(f).Encode(g)` | `codec(T, Out, { decode: f, encode: g })` |
454
- | `Value.Decode(T, x)`, `Value.Encode(T, x)` | `T.assert(x)`, `T.encode.assert(x)` |
455
- | `{ default: x }` with `Value.Default` | `"key": "T = x"` |
456
- | `Static<typeof T>`, `StaticDecode`, `StaticEncode` | `typeof T.infer`, `typeof T.infer`, `typeof T.inferIn` |
457
- | `Value.Check(T, x)`, `Value.Parse`, `TypeCompiler.Compile` | `T.allows(x)`, `T.assert(x)`, nothing to compile |
1086
+ TypeBox schemas are JSON Schema, so [JSON Schema](#json-schema-and-ajv) also applies. `Type.Optional` and `Type.Partial` accept a key present as `undefined`, and `Value.Default` replaces it: write `| undefined` at each key, or [configure](#defaults-that-differ) `exactOptionalPropertyTypes: false`.
1087
+
1088
+ Names are `@sinclair/typebox` 0.34's. TypeBox 1, the `typebox` package, renames some: `Type.Recursive` is `Type.Cyclic`, `Type.Transform` is `Type.Codec`, `Type.Composite` is `Type.Evaluate` of a `Type.Intersect`, and `TypeCompiler.Compile` is `Compile` from `typebox/compile`.
1089
+
1090
+ | TypeBox | ArkType |
1091
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
1092
+ | `Type.Object({...})`, `{ additionalProperties: false }` | `type({...})`, `"+": "reject"` |
1093
+ | `Type.Optional(T)` | `"key?": "T \| undefined"` |
1094
+ | `Type.String({ minLength, maxLength, pattern })` | `"1 <= string <= 255"`, `/pattern/` |
1095
+ | `Type.String({ format: "email" })` | `"string.email"` |
1096
+ | `Type.String({ description, title, examples })` | `.describe(text)`, see [Descriptions](#descriptions); `.configure({ title, examples })` |
1097
+ | `Type.Number({ minimum, exclusiveMaximum })`, `Type.Integer()` | `"0 <= number < 10"`, `"number.integer"` |
1098
+ | `Type.Literal`, `Type.Union`, `Type.Enum(E)` | `"'a'"`, `A.or(B)`, `type.valueOf(E)` |
1099
+ | `Type.Array(T, { minItems })`, `Type.Tuple` | `"T[] >= 1"`, `[A, B]` |
1100
+ | `Type.Record(Type.String(), T)` | `"Record<string, T>"` |
1101
+ | `Type.Intersect`, `Type.Composite` | `A.and(B)` for both: a key in both must satisfy both |
1102
+ | `Type.Partial`, `Type.Pick`, `Type.Omit`, `Type.KeyOf` | `.partial()`, `.pick()`, `.omit()`, `.keyof()` |
1103
+ | `Type.Recursive(This => ...)` | `this` or a scope |
1104
+ | `Type.Date()`, `Type.Unknown()`, `Type.Any()` | `"Date"`, `"unknown"`, `"unknown.any"` |
1105
+ | `Type.Transform(T).Decode(f).Encode(g)` | `codec(T, Out, { decode: f, encode: g })` |
1106
+ | `Value.Decode(T, x)`, `Value.Encode(T, x)` | `T.assert(x)`, `T.encode.assert(x)` |
1107
+ | `{ default: x }` with `Value.Default` | `"key": "T = x"` |
1108
+ | `Static<typeof T>`, `StaticDecode`, `StaticEncode` | `typeof T.infer`, `typeof T.infer`, `typeof T.inferIn` |
1109
+ | `Value.Check(T, x)`, `Value.Parse`, `TypeCompiler.Compile` | `T.allows(x)`, `T.assert(x)`, nothing to compile |
1110
+ | `Value.Errors(T, x)` | `T(x)`, then `out.issues`, each with a `path` like `["tags", 1, "label"]` where TypeBox's is `/tags/1/label` |
458
1111
 
459
1112
  ## Yup
460
1113
 
461
- 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](#defaults-that-differ) has the pattern that keeps it.
1114
+ Yup does more to a value before checking it than ArkType does:
1115
+
1116
+ - It converts values unless `.strict()`. Translate what the data actually is: a form posting strings needs `"string.numeric.parse"` where `number()` converted.
1117
+ - A field is optional unless `.required()`, which for a string also rejects `""`.
1118
+ - It applies a default to a key present as `undefined`, where `"key": "T = x"` rejects it. [Defaults that differ](#defaults-that-differ) has the pattern that keeps it. Yup 1 leaves a key given `undefined` out of what it returns, where a Type that accepts it returns it.
1119
+ - `.email()` and `.url()` pass an empty string, so a field that isn't `.required()` is `"string.email | ''"`.
1120
+ - It reads a date string without an offset in local time, where `string.date.parse` reads it as UTC.
462
1121
 
463
1122
  | Yup | ArkType |
464
1123
  | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -469,6 +1128,9 @@ Yup converts values unless `.strict()`, and treats a field as optional unless `.
469
1128
  | `.email()`, `.url()`, `.uuid()`, `.matches(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
470
1129
  | `.min(n)`, `.max(n)`, `.length(n)` on strings, arrays | `"string >= n"`, `"T[] <= n"`, `"string == n"` |
471
1130
  | `.integer()`, `.positive()`, `.moreThan(n)` | `"number.integer"`, `"number > 0"`, `"number > n"` |
1131
+ | `number()`, `date()` reading strings | `"number \| string.numeric.parse"`, `"Date \| string.date.parse"` |
1132
+ | `.required("m")`, `.typeError("m")`, `.min(n, "m")` | `.configure({ message: "m" }, "self")`, then `"domain"`, then `"minLength"` or `"min"` for a number; see below |
1133
+ | `.concat(S)`, `.pick(["a"])`, `.omit(["a"])` | `.merge(S)`, `.pick("a")`, `.omit("a")` |
472
1134
  | `.trim()`, `.lowercase()` | `"string.trim"`, `"string.lower"` |
473
1135
  | `.oneOf(["a", "b"])` | `"'a' \| 'b'"` |
474
1136
  | `array().of(T)`, `tuple([A, B])` | `T.array()`, `[A, B]` |
@@ -477,85 +1139,158 @@ Yup converts values unless `.strict()`, and treats a field as optional unless `.
477
1139
  | `.transform(fn)` | `.pipe(fn)` |
478
1140
  | `.when("other", ...)` | a union of the cases, or a `.narrow()` on the object |
479
1141
  | `lazy` | a scope or `this` |
480
- | `.noUnknown()`, `stripUnknown: true` | `"+": "reject"`, `"+": "delete"` |
1142
+ | `.noUnknown()`, `stripUnknown: true` | `"+": "delete"` for both, since `.noUnknown()` removes the keys too, and `"+": "reject"` where it's validated with `strict: true` |
481
1143
  | `InferType<typeof S>` | `typeof T.infer` |
482
1144
  | `validateSync(x)`, `isValidSync(x)`, `validate(x)` | `T.assert(x)`, `T.allows(x)`, `T(x)` |
1145
+ | `error.inner`, each with a `path` and `message` | `out.issues`, or `flatMessagesByPath(out)`, keyed by paths written like Yup's, such as `tags[1].name` |
1146
+ | `yupResolver(S)` (react-hook-form) | `standardSchemaResolver(T)` from `@hookform/resolvers/standard-schema` |
1147
+ | Formik's `validationSchema: S` | `validate`, as below |
1148
+
1149
+ `.required("m")` says `m` for a missing key, for `undefined` and, on a string, for `""`, before any other check. Configure `m` for each, choosing an empty string's text from the value as [Custom messages](#custom-messages) shows:
1150
+
1151
+ ```ts
1152
+ // yup.string().required("Email is required").email("Enter a valid email")
1153
+ const Email = type("string.email")
1154
+ .configure(
1155
+ {
1156
+ message: error =>
1157
+ error.data === "" ? "Email is required" : "Enter a valid email"
1158
+ },
1159
+ "pattern"
1160
+ )
1161
+ .configure({ message: "Email is required" }, "self")
1162
+ .configure({ message: "Email is required" }, "domain")
1163
+ ```
1164
+
1165
+ A field that transforms, like one with `.trim()` or a `number()` reading strings, says ArkType's text for a missing key unless one message covers its whole value.
1166
+
1167
+ Formik reads errors nested like the values. Its `setIn` builds that from each issue's path, as its `yupToFormErrors` does:
1168
+
1169
+ ```ts
1170
+ import { type } from "arktype"
1171
+ import { getIn, setIn } from "formik"
1172
+
1173
+ const Form = type({ name: "string > 0", tags: "string[]" })
1174
+
1175
+ const validate = (values: unknown) => {
1176
+ const out = Form(values)
1177
+ let errors = {}
1178
+ if (out instanceof type.errors)
1179
+ for (const issue of out.issues) {
1180
+ const path = issue.path.join(".")
1181
+ if (!getIn(errors, path)) errors = setIn(errors, path, issue.message)
1182
+ }
1183
+ return errors
1184
+ }
1185
+ ```
483
1186
 
484
1187
  ## Joi
485
1188
 
486
- 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](#defaults-that-differ). It infers no types, so `typeof T.infer` replaces the interfaces written next to Joi schemas.
487
-
488
- | Joi | ArkType |
489
- | ---------------------------------------------- | ------------------------------------------------------------------------------ |
490
- | `Joi.object({...})`, `.unknown(true)` | `type({ "+": "reject", ... })`, `type({...})` |
491
- | `Joi.string()` (optional), `.required()` | `"key?": "string > 0 \| undefined"`, `"key": "string > 0"` |
492
- | `.allow("")`, `.allow(null)` | `"string"`, `"string \| null"` |
493
- | `.valid("a", "b")` | `"'a' \| 'b'"` |
494
- | `.email()`, `.uri()`, `.guid()`, `.pattern(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
495
- | `.min(n)`, `.max(n)`, `.length(n)` | `"string >= n"`, `"string <= n"`, `"string == n"` |
496
- | `Joi.number().integer().positive()` | `"number.integer > 0"` |
497
- | `Joi.number()` reading strings | `"number \| string.numeric.parse"` |
498
- | `Joi.boolean()` reading strings | `type("boolean \| 'true' \| 'false'").pipe(v => v === true \|\| v === "true")` |
499
- | `Joi.date()`, `Joi.date().iso()` | `"Date \| string.date.parse"`, `"string.date.iso.parse"` |
500
- | `Joi.array().items(T)`, `.min(1)` | `T.array()`, `"T[] >= 1"` |
501
- | `.unique()` | `.narrow((a, ctx) => new Set(a).size === a.length \|\| ctx.reject("unique"))` |
502
- | `Joi.alternatives().try(A, B)` | `A.or(B)` |
503
- | `.default(x)` | `"key": "T = x"` |
504
- | `.custom(fn)` | `.narrow()` or `.pipe()` |
505
- | `.messages({...})` | `.configure({ message })` |
506
- | `Joi.link("#id")` | a scope or `this` |
507
- | `.when(...)` | a union of the cases, or a `.narrow()` on the object |
508
- | `schema.validate(x)`, `.attempt(x, schema)` | `T(x)`, `T.assert(x)` |
1189
+ 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](#defaults-that-differ). It infers no types, so `typeof T.infer` replaces the interfaces written next to Joi schemas. `validate` reports the first error unless `abortEarly: false`, where a Type reports every one. Joi's conversions take a little more than the rows below: `Joi.boolean()` reads `"TRUE"` and `Joi.number()` reads `" 2"`.
1190
+
1191
+ | Joi | ArkType |
1192
+ | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
1193
+ | `Joi.object({...})`, `.unknown(true)` | `type({ "+": "reject", ... })`, `type({...})` |
1194
+ | `Joi.string()` (optional), `.required()` | `"key?": "string > 0 \| undefined"`, `"key": "string > 0"` |
1195
+ | `.allow("")`, `.allow(null)` | `"string"`, `"string \| null"` |
1196
+ | `.valid("a", "b")` | `"'a' \| 'b'"` |
1197
+ | `.email()`, `.uri()`, `.guid()`, `.pattern(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
1198
+ | `.alphanum()`, `.token()`, `.hex()`, `.ip()`, `.isoDate()` | `"string.alphanumeric > 0"`, `/^\w+$/`, `"string.hex"`, `"string.ip"`, `"string.date.iso"` |
1199
+ | `.trim()`, `.lowercase()`, `.uppercase()` | `"string.trim"`, `"string.lower"`, `"string.upper"`, each with `.to("string > 0")` |
1200
+ | `.min(n)`, `.max(n)`, `.length(n)` | `"string >= n"`, `"string <= n"`, `"string == n"` |
1201
+ | `Joi.number().integer().positive()` | `"number.integer > 0"` |
1202
+ | `Joi.number()` reading strings | `"number \| string.numeric.parse"` |
1203
+ | `Joi.boolean()` reading strings | `type("boolean \| 'true' \| 'false'").pipe(v => v === true \|\| v === "true")` |
1204
+ | `Joi.date()`, `Joi.date().iso()` | `"Date \| string.date.parse"`, `"string.date.iso.parse"` |
1205
+ | `Joi.date()` reading milliseconds | `type("number.epoch").pipe(n => new Date(n))` |
1206
+ | `Joi.array().items(T)`, `.min(1)` | `T.array()`, `"T[] >= 1"` |
1207
+ | `.unique()` | `.narrow((a, ctx) => new Set(a).size === a.length \|\| ctx.reject("unique"))` |
1208
+ | `Joi.alternatives().try(A, B)` | `A.or(B)` |
1209
+ | `.default(x)` | `"key": "T = x"` |
1210
+ | `.custom(fn)` | `.narrow()` or `.pipe()` |
1211
+ | `.messages({ "any.required": m })`, `"string.base"`, `"string.min"`, `"number.min"` | `.configure({ message: m }, "self")`, then `"domain"`, `"minLength"`, `"min"`; see [Custom messages](#custom-messages) |
1212
+ | `Joi.link("#id")` | a scope or `this` |
1213
+ | `.when(...)` | a union of the cases, or a `.narrow()` on the object |
1214
+ | `Joi.valid(Joi.ref("a"))`, `.with("a", "b")`, `.xor("a", "b")`, `.or("a", "b")` | a `.narrow()` on the object that compares the keys or checks which are present |
1215
+ | `Joi.any()`, `.forbidden()` | `"unknown"`, `"key?": "never"` |
1216
+ | `{ stripUnknown: true }` | `"+": "delete"` in each object, or `configure({ onUndeclaredKey: "delete" })` |
1217
+ | `schema.validate(x)`, `.attempt(x, schema)` | `T(x)`, `T.assert(x)` |
509
1218
 
510
1219
  ## Effect Schema
511
1220
 
512
- 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`.
513
-
514
- | Effect Schema | ArkType |
515
- | --------------------------------------------------------------- | -------------------------------------------------------------------- |
516
- | `Schema.Struct({...})` | `type({ "+": "delete", ... })` |
517
- | `Schema.optional(T)`, `Schema.optionalWith(T, { exact: true })` | `"key?": "T \| undefined"`, `"key?": "T"` |
518
- | `Schema.optionalWith(T, { default: () => x })` | `"key": "T = x"` |
519
- | `Schema.NullOr`, `Schema.NullishOr` | `"T \| null"`, `"T \| null \| undefined"` |
520
- | `Schema.Literal("a", "b")`, `Schema.Enums(E)` | `"'a' \| 'b'"`, `type.valueOf(E)` |
521
- | `Schema.Union(A, B)`, `Schema.TaggedStruct` | `A.or(B)`, an object with a literal `_tag` |
522
- | `Schema.Array`, `Schema.NonEmptyArray`, `Schema.Tuple` | `"T[]"`, `"T[] >= 1"`, `[A, B]` |
523
- | `Schema.Record({ key: Schema.String, value: T })` | `"Record<string, T>"` |
524
- | `Schema.suspend(() => T)` | a scope or `this` |
525
- | `Schema.Int`, `Schema.Positive`, `Schema.between(a, b)` | `"number.integer"`, `"number > 0"`, `"a <= number <= b"` |
526
- | `Schema.minLength`, `Schema.pattern(r)`, `Schema.UUID` | `"string >= n"`, `/r/`, `"string.uuid"` |
527
- | `Schema.NumberFromString`, `Schema.DateFromString` | `"string.numeric.parse"`, `"string.date.parse"` |
528
- | `Schema.Trim`, `Schema.Lowercase`, `Schema.parseJson(T)` | `"string.trim"`, `"string.lower"`, `type("string.json.parse").to(T)` |
529
- | `Schema.filter(fn)` | `.narrow(fn)` |
530
- | `Schema.transform(From, To, { decode, encode })` | `codec(From, To, { decode, encode })` |
531
- | `Schema.brand("Id")` | `.brand("Id")` |
532
- | `Schema.Type<typeof S>`, `Schema.Encoded<typeof S>` | `typeof T.infer`, `typeof T.inferIn` |
533
- | `Schema.decodeUnknownSync`, `decodeUnknownEither` | `T.assert(x)`, `T(x)` |
534
- | `Schema.encodeSync`, `encodeEither` | `T.encode.assert(x)`, `T.encode(x)` |
535
- | `onExcessProperty: "error"` | `"+": "reject"` |
1221
+ Effect 4 renamed much of Effect 3's Schema API, so each row gives both. In Effect 4, an `is…` check or `makeFilter` goes inside `S.check(...)`.
1222
+
1223
+ Three defaults differ in both versions:
1224
+
1225
+ - **`Schema.Number` allows `NaN` and `Infinity`**, which `"number"` rejects, like `Schema.Finite`. To keep them, write `"number | number.NaN | number.Infinity | number.NegativeInfinity"`.
1226
+ - **A default without `exact` fills a key present as `undefined`**, where `"key": "T = x"` rejects it. That is `optionalWith(T, { default })` in Effect 3 and `withDecodingDefault` in Effect 4. [Defaults that differ](#defaults-that-differ) has the pattern that keeps it.
1227
+ - **`string.numeric.parse` is stricter than `NumberFromString`**, which reads `" 1 "` and `"0x10"`. In Effect 4 it also turns `"abc"` into `NaN`, and `FiniteFromString` reads `""` as `0`.
1228
+
1229
+ | Effect 3 | Effect 4 | ArkType |
1230
+ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- |
1231
+ | `Schema.Struct({...})` | same | `type({ "+": "delete", ... })` |
1232
+ | `Schema.optional(T)` | same | `"key?": "T \| undefined"` |
1233
+ | `Schema.optionalWith(T, { exact: true })` | `Schema.optionalKey(T)` | `"key?": "T"` |
1234
+ | `Schema.optionalWith(T, { default: () => x, exact: true })` | `T.pipe(Schema.withDecodingDefaultKey(Effect.succeed(x)))` | `"key": "T = x"` |
1235
+ | `Schema.NullOr(T)`, `Schema.NullishOr(T)` | same | `"T \| null"`, `"T \| null \| undefined"` |
1236
+ | `Schema.Literal("a", "b")` | `Schema.Literals(["a", "b"])` | `"'a' \| 'b'"` |
1237
+ | `Schema.Enums(E)` | `Schema.Enum(E)` | `type.valueOf(E)` |
1238
+ | `Schema.Union(A, B)` | `Schema.Union([A, B])` | `A.or(B)` |
1239
+ | `Schema.TaggedStruct("A", {...})` | same | an object with `_tag: "'A'"` |
1240
+ | `Schema.Array(T)`, `Schema.NonEmptyArray(T)` | same | `"T[]"`, `"T[] >= 1"` |
1241
+ | `Schema.Tuple(A, B)` | `Schema.Tuple([A, B])` | `[A, B]` |
1242
+ | `Schema.Record({ key: Schema.String, value: T })` | `Schema.Record(Schema.String, T)` | `"Record<string, T>"` |
1243
+ | `Schema.suspend(() => T)` | same | a scope or `this` |
1244
+ | `Schema.Finite`, `Schema.Int` | same | `"number"`, `"number.integer"` |
1245
+ | `Schema.Positive` | `Schema.isGreaterThan(0)` | `"number > 0"` |
1246
+ | `Schema.between(a, b)` | `Schema.isBetween({ minimum: a, maximum: b })` | `"a <= number <= b"` |
1247
+ | `Schema.minLength(n)`, `Schema.pattern(r)` | `Schema.isMinLength(n)`, `Schema.isPattern(r)` | `"string >= n"`, `/r/` |
1248
+ | `Schema.UUID` | `Schema.isUUID()` | `"string.uuid"` |
1249
+ | `Schema.NumberFromString` | `Schema.FiniteFromString` | `"string.numeric.parse"` |
1250
+ | `Schema.Date` | `Schema.DateFromString` | `"string.date.parse"` |
1251
+ | `Schema.ValidDateFromSelf` | `Schema.Date` | `"Date"` |
1252
+ | `Schema.Trim`, `Schema.Lowercase` | `Schema.Trim`, `SchemaTransformation.toLowerCase()` | `"string.trim"`, `"string.lower"` |
1253
+ | `Schema.parseJson(T)` | `Schema.fromJsonString(T)` | `type("string.json.parse").to(T)` |
1254
+ | `Schema.filter(fn)` | `Schema.makeFilter(fn)` | `.narrow(fn)` |
1255
+ | `Schema.transform(From, To, { decode, encode })` | `From.pipe(Schema.decodeTo(To, SchemaTransformation.transform({ decode, encode })))` | `codec(From, To, { decode, encode })` |
1256
+ | `Schema.brand("Id")` | same | `.brand("Id")` |
1257
+ | `S.annotations({ description, title })` | `S.annotate({ description, title })` | `.describe(text)`, see [Descriptions](#descriptions); `.configure({ title })` |
1258
+ | `typeof S.Type`, `typeof S.Encoded` | same | `typeof T.infer`, `typeof T.inferIn` |
1259
+ | `Schema.decodeUnknownSync(S)(x)` | same | `T.assert(x)` |
1260
+ | `Schema.decodeUnknownEither(S)(x)` | `Schema.decodeUnknownResult(S)(x)` | `T(x)` |
1261
+ | `Schema.encodeSync(S)(x)`, `Schema.encodeEither(S)(x)` | `Schema.encodeSync(S)(x)`, `Schema.encodeResult(S)(x)` | `T.encode.assert(x)`, `T.encode(x)` |
1262
+ | `onExcessProperty: "error"` | same | `"+": "reject"` |
536
1263
 
537
1264
  `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.
538
1265
 
1266
+ To move one schema at a time, wrap an Effect schema as a [Standard Schema](https://arktype.io/docs/standard-schema) and use it in a definition: `Schema.standardSchemaV1(S)` in Effect 3, `Schema.toStandardSchemaV1(S)` in Effect 4.
1267
+
539
1268
  ## JSON Schema and ajv
540
1269
 
541
1270
  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:
542
1271
 
543
- | JSON Schema | ArkType |
544
- | -------------------------------------------------------- | ---------------------------------------------------------------------- |
545
- | `{ type: "string", minLength: 1, maxLength: 255 }` | `"1 <= string <= 255"` |
546
- | `{ type: "string", pattern: "^a" }` | `/^a/` |
547
- | `{ type: "integer", minimum: 0, exclusiveMaximum: 10 }` | `"0 <= number.integer < 10"` |
548
- | `{ multipleOf: 5 }` | `"number % 5"` |
549
- | `{ enum: ["a", "b"] }`, `{ const: "a" }` | `"'a' \| 'b'"`, `"'a'"` |
550
- | `{ type: ["string", "null"] }`, `anyOf`, `oneOf` | `"string \| null"`, `A.or(B)` |
551
- | `allOf` | `A.and(B)` |
552
- | `properties` with `required` | keys, with `?` on those not required |
553
- | `additionalProperties: false`, `additionalProperties: T` | `"+": "reject"`, `"[string]": "T \| A"`, `A` the declared keys' types |
554
- | `patternProperties: { "^x-": T }` | `"[/^x-/]": T` |
555
- | `{ type: "array", items: T, minItems: 1 }` | `"T[] >= 1"` |
556
- | `prefixItems` | `[A, B]` |
557
- | `$defs` with `$ref` | a scope |
558
- | `format: "email"`, `"uuid"`, `"date-time"`, `"uri"` | `"string.email"`, `"string.uuid"`, `"string.date.iso"`, `"string.url"` |
559
- | `default` | `"key": "T = x"` |
1272
+ | JSON Schema | ArkType |
1273
+ | ------------------------------------------------------- | ---------------------------------------------------------------------- |
1274
+ | `{ type: "string", minLength: 1, maxLength: 255 }` | `"1 <= string <= 255"` |
1275
+ | `{ type: "string", pattern: "^a" }` | `/^a/` |
1276
+ | `{ type: "integer", minimum: 0, exclusiveMaximum: 10 }` | `"0 <= number.integer < 10"` |
1277
+ | `{ multipleOf: 5 }` | `"number % 5"` |
1278
+ | `{ multipleOf: 0.01 }`, `uniqueItems: true` | a `.narrow()`, as for Zod's `.multipleOf(0.01)` and Joi's `.unique()` |
1279
+ | `{ enum: ["a", "b"] }`, `{ const: "a" }` | `"'a' \| 'b'"`, `"'a'"` |
1280
+ | `{ type: ["string", "null"] }`, `anyOf` | `"string \| null"`, `A.or(B)` |
1281
+ | `oneOf` | `A.or(B)`, which also accepts data matching both |
1282
+ | `allOf` | `A.and(B)` |
1283
+ | `properties` with `required` | keys, with `?` on those not required |
1284
+ | `additionalProperties: false` | `"+": "reject"` |
1285
+ | `additionalProperties: T` | `"[/^(?!a$\|b$)/]": T`, `a` and `b` the declared keys |
1286
+ | `patternProperties: { "^x-": T }` | `"[/^x-/]": T` |
1287
+ | `{ type: "array", items: T, minItems: 1 }` | `"T[] >= 1"` |
1288
+ | `prefixItems: [A, B]` | `["A?", "B?", "...", "unknown[]"]`: shorter and longer arrays pass |
1289
+ | the same with `items: false` and `minItems: 2` | `[A, B]` |
1290
+ | `$defs` with `$ref` | a scope |
1291
+ | `format: "email"`, `"uuid"`, `"date-time"`, `"uri"` | `"string.email"`, `"string.uuid"`, `"string.date.iso"`, `"string.url"` |
1292
+ | `default` | `"key": "T = x"` |
1293
+
1294
+ With `ajv-formats`, `date-time` requires a time and an offset, which `string.date.iso` doesn't: intersect a pattern, as in [Dates and formats](#dates-and-formats).
560
1295
 
561
1296
  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.