arktype 2.2.10 → 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.
- package/README.md +181 -15
- package/out/attributes.d.ts +50 -14
- package/out/checkers.d.ts +172 -0
- package/out/chunk-2U2AWCI3.js +626 -0
- package/out/chunk-4CUA5XIP.js +7 -0
- package/out/chunk-5U2ZMDNI.js +1566 -0
- package/out/chunk-DLWCO4RV.js +18 -0
- package/out/chunk-E3DZXEZK.js +72 -0
- package/out/chunk-EVCML554.js +47 -0
- package/out/chunk-G45P2CLE.js +63 -0
- package/out/chunk-GPNK5353.js +2529 -0
- package/out/chunk-MLKGABMK.js +9 -0
- package/out/chunk-NRIGTMPM.js +7 -0
- package/out/chunk-PRTMQCHS.js +3 -0
- package/out/chunk-R5G57XC7.js +7 -0
- package/out/chunk-RAZ3TXOE.js +313 -0
- package/out/chunk-SWOOCAHN.js +4 -0
- package/out/chunk-TAHPKDNM.js +3 -0
- package/out/chunk-UETB6YE2.js +14 -0
- package/out/chunk-UK5UGFOX.js +254 -0
- package/out/chunk-VV6YDN2D.js +6118 -0
- package/out/codecs.d.ts +21 -0
- package/out/codecs.js +7 -0
- package/out/config.d.ts +8 -3
- package/out/config.js +2 -3
- package/out/declare.d.ts +17 -3
- package/out/deferred.d.ts +10 -0
- package/out/errors.d.ts +1 -0
- package/out/errors.js +2 -0
- package/out/fn.d.ts +1 -1
- package/out/generic.d.ts +3 -3
- package/out/i18n.d.ts +2 -0
- package/out/i18n.js +2 -0
- package/out/index.d.ts +5 -4
- package/out/index.js +8 -9
- package/out/internal.d.ts +70 -0
- package/out/internal.js +17 -0
- package/out/island.d.ts +2 -0
- package/out/island.js +6 -0
- package/out/islandDependency.d.ts +2 -0
- package/out/islandDependency.js +18 -0
- package/out/keywords/Array.d.ts +2 -2
- package/out/keywords/builtins.d.ts +5 -3
- package/out/keywords/constructors.d.ts +9 -1
- package/out/keywords/functions.d.ts +254 -0
- package/out/keywords/keywords.d.ts +8 -9
- package/out/keywords/number.d.ts +2 -8
- package/out/keywords/phrases.d.ts +245 -0
- package/out/keywords/string.d.ts +14 -113
- package/out/keywords/ts.d.ts +35 -33
- package/out/keywords/ts.js +4 -82
- package/out/locale.d.ts +19 -0
- package/out/locales/de.d.ts +2 -0
- package/out/locales/de.js +2 -0
- package/out/locales/en.d.ts +4 -0
- package/out/locales/en.js +5 -0
- package/out/match.d.ts +6 -6
- package/out/module.d.ts +1 -1
- package/out/mutatesInput.js +3 -0
- package/out/parser/ast/generic.d.ts +6 -3
- package/out/parser/ast/infer.d.ts +1 -1
- package/out/parser/ast/validate.d.ts +11 -6
- package/out/parser/definition.d.ts +68 -7
- package/out/parser/objectLiteral.d.ts +40 -12
- package/out/parser/property.d.ts +3 -5
- package/out/parser/reduce/dynamic.d.ts +16 -7
- package/out/parser/reduce/shared.d.ts +4 -0
- package/out/parser/reduce/static.d.ts +13 -13
- package/out/parser/shift/operand/date.d.ts +0 -5
- package/out/parser/shift/operand/operand.d.ts +2 -1
- package/out/parser/shift/operand/unenclosed.d.ts +9 -6
- package/out/parser/shift/operand/unresolvable.d.ts +68 -0
- package/out/parser/shift/operator/bounds.d.ts +9 -4
- package/out/parser/shift/operator/brand.d.ts +2 -2
- package/out/parser/shift/operator/default.d.ts +2 -2
- package/out/parser/shift/operator/divisor.d.ts +2 -2
- package/out/parser/shift/operator/operator.d.ts +1 -1
- package/out/parser/shift/tokens.d.ts +9 -2
- package/out/parser/string.d.ts +61 -7
- package/out/parser/tupleExpressions.d.ts +7 -3
- package/out/precompiled.d.ts +1 -0
- package/out/precompiled.js +2 -0
- package/out/runtime.d.ts +181 -0
- package/out/runtime.js +4 -0
- package/out/runtimeDevelopment.d.ts +1 -0
- package/out/runtimeDevelopment.js +133 -0
- package/out/runtimeExports.d.ts +1 -0
- package/out/scope.d.ts +40 -11
- package/out/standalone/artifact.d.ts +265 -0
- package/out/standalone/baking.d.ts +201 -0
- package/out/standalone/combinators.d.ts +13 -0
- package/out/standalone/compilers.d.ts +23 -0
- package/out/standalone/creators.d.ts +41 -0
- package/out/standalone/fallbacks.d.ts +48 -0
- package/out/standalone/keys.d.ts +31 -0
- package/out/standalone/modules.d.ts +26 -0
- package/out/standalone/sites.d.ts +52 -0
- package/out/standalone/units.d.ts +31 -0
- package/out/standalone/values.d.ts +60 -0
- package/out/standalone.d.ts +16 -0
- package/out/type.d.ts +45 -6
- package/out/variants/array.d.ts +1 -1
- package/out/variants/base.d.ts +47 -27
- package/out/variants/date.d.ts +1 -1
- package/out/variants/instantiate.d.ts +4 -2
- package/out/variants/number.d.ts +1 -1
- package/out/variants/object.d.ts +17 -12
- package/out/variants/string.d.ts +1 -1
- package/package.json +169 -8
- package/skills/arktype/SKILL.md +278 -43
- package/skills/arktype/references/migrating.md +1296 -0
- package/skills/arktype/references/precompile.md +191 -0
- package/out/attributes.js +0 -3
- package/out/fn.js +0 -58
- package/out/generic.js +0 -37
- package/out/keywords/Array.js +0 -21
- package/out/keywords/FormData.js +0 -40
- package/out/keywords/TypedArray.js +0 -16
- package/out/keywords/builtins.js +0 -11
- package/out/keywords/constructors.js +0 -16
- package/out/keywords/keywords.js +0 -48
- package/out/keywords/number.js +0 -49
- package/out/keywords/string.js +0 -467
- package/out/match.js +0 -95
- package/out/module.js +0 -3
- package/out/nary.js +0 -1
- package/out/parser/ast/bounds.js +0 -1
- package/out/parser/ast/default.js +0 -1
- package/out/parser/ast/divisor.js +0 -1
- package/out/parser/ast/generic.js +0 -1
- package/out/parser/ast/infer.js +0 -1
- package/out/parser/ast/keyof.js +0 -1
- package/out/parser/ast/utils.js +0 -1
- package/out/parser/ast/validate.js +0 -3
- package/out/parser/definition.js +0 -78
- package/out/parser/objectLiteral.js +0 -113
- package/out/parser/property.js +0 -16
- package/out/parser/reduce/dynamic.js +0 -153
- package/out/parser/reduce/shared.js +0 -25
- package/out/parser/reduce/static.js +0 -1
- package/out/parser/shift/operand/date.js +0 -23
- package/out/parser/shift/operand/enclosed.js +0 -82
- package/out/parser/shift/operand/genericArgs.js +0 -16
- package/out/parser/shift/operand/operand.js +0 -16
- package/out/parser/shift/operand/unenclosed.js +0 -59
- package/out/parser/shift/operator/bounds.js +0 -91
- package/out/parser/shift/operator/brand.js +0 -6
- package/out/parser/shift/operator/default.js +0 -29
- package/out/parser/shift/operator/divisor.js +0 -13
- package/out/parser/shift/operator/operator.js +0 -28
- package/out/parser/shift/tokens.js +0 -37
- package/out/parser/string.js +0 -42
- package/out/parser/tupleExpressions.js +0 -75
- package/out/parser/tupleLiteral.js +0 -128
- package/out/scope.js +0 -106
- package/out/type.js +0 -55
- package/out/variants/array.js +0 -1
- package/out/variants/base.js +0 -1
- package/out/variants/date.js +0 -1
- package/out/variants/instantiate.js +0 -1
- package/out/variants/number.js +0 -1
- package/out/variants/object.js +0 -1
- package/out/variants/string.js +0 -1
- /package/out/{declare.js → mutatesInput.d.ts} +0 -0
|
@@ -0,0 +1,1296 @@
|
|
|
1
|
+
# Migrating to ArkType
|
|
2
|
+
|
|
3
|
+
<!-- written from ark/docs/content/docs/(arktype)/migrating.mdx when the docs build; edit that instead -->
|
|
4
|
+
|
|
5
|
+
How to convert schemas from Zod (v3, v4 and Zod Mini), Valibot, TypeBox, Yup, Joi, Effect Schema and JSON Schema to ArkType.
|
|
6
|
+
|
|
7
|
+
## Migrating a project
|
|
8
|
+
|
|
9
|
+
To move a whole project off Zod, or another library below, work through it in this order.
|
|
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. 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).
|
|
26
|
+
4. **Update call sites.**
|
|
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`:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// error.flatten() or z.flattenError(error)
|
|
37
|
+
const formErrors: string[] = []
|
|
38
|
+
const fieldErrors: Record<string, string[]> = {}
|
|
39
|
+
for (const issue of out.issues) {
|
|
40
|
+
if (issue.path.length === 0) formErrors.push(issue.message)
|
|
41
|
+
else (fieldErrors[String(issue.path[0])] ??= []).push(issue.message)
|
|
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
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
5. **Swap integrations.** Most accept an ArkType type directly, through [Standard Schema](https://arktype.io/docs/standard-schema):
|
|
64
|
+
|
|
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 |
|
|
86
|
+
|
|
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`.
|
|
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
|
+
|
|
93
|
+
Without casts:
|
|
94
|
+
|
|
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)`.
|
|
97
|
+
- The MCP SDK finds a prompt argument's completer through Zod's `.shape`, so give `argsSchema` one, as below.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { completable } from "@modelcontextprotocol/server"
|
|
101
|
+
import { type } from "arktype"
|
|
102
|
+
|
|
103
|
+
const Args = type({ language: "string" })
|
|
104
|
+
const argsSchema = {
|
|
105
|
+
"~standard": Args["~standard"],
|
|
106
|
+
shape: {
|
|
107
|
+
language: completable({ "~standard": type("string")["~standard"] }, value =>
|
|
108
|
+
["typescript", "python"].filter(l => l.startsWith(value))
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
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.
|
|
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.
|
|
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.
|
|
119
|
+
|
|
120
|
+
## Zod side by side
|
|
121
|
+
|
|
122
|
+
A Zod schema:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { z } from "zod"
|
|
126
|
+
|
|
127
|
+
const User = z.object({
|
|
128
|
+
name: z.string().min(1, "Name is required"),
|
|
129
|
+
email: z.email(),
|
|
130
|
+
age: z.number().int().nonnegative().optional(),
|
|
131
|
+
role: z.enum(["admin", "member"]).default("member")
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
type User = z.infer<typeof User>
|
|
135
|
+
|
|
136
|
+
const result = User.safeParse(data)
|
|
137
|
+
|
|
138
|
+
if (!result.success) console.error(z.prettifyError(result.error))
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The same in ArkType:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
import "./arktype.config.ts"
|
|
145
|
+
import { type } from "arktype"
|
|
146
|
+
|
|
147
|
+
const User = type({
|
|
148
|
+
name: ["string >= 1", "@", { message: "Name is required" }],
|
|
149
|
+
email: "string.email",
|
|
150
|
+
"age?": "number.integer >= 0",
|
|
151
|
+
role: "'admin' | 'member' = 'member'"
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
type User = typeof User.infer
|
|
155
|
+
|
|
156
|
+
const out = User(data)
|
|
157
|
+
|
|
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
|
+
})
|
|
173
|
+
```
|
|
174
|
+
|
|
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.
|
|
176
|
+
|
|
177
|
+
## Zod
|
|
178
|
+
|
|
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) |
|
|
410
|
+
|
|
411
|
+
## Defaults that differ
|
|
412
|
+
|
|
413
|
+
| Behavior | ArkType | Zod | Valibot | TypeBox `Value.Check` | Yup | Joi | Effect Schema |
|
|
414
|
+
| --------------------------------------------- | ------------------ | ------------------ | -------- | --------------------- | -------------------- | ------------------------- | ------------- |
|
|
415
|
+
| Undeclared object keys | kept | removed | removed | allowed | kept | rejected | removed |
|
|
416
|
+
| Optional key present with the value undefined | rejected | accepted | accepted | accepted | accepted | accepted | accepted |
|
|
417
|
+
| Default applied when the value is undefined | no, only if absent | yes | yes | only `Value.Default` | yes | yes | yes |
|
|
418
|
+
| Converts input types, e.g. `"12"` to `12` | only when parsing | only in `z.coerce` | no | only `Value.Convert` | yes, unless strict | yes, unless convert false | no |
|
|
419
|
+
| `number` accepts `Infinity` | no | v4: no, v3: yes | yes | no | yes | no | yes |
|
|
420
|
+
| `number` accepts `NaN` | no | no | no | no | no | no | yes |
|
|
421
|
+
| An array where an object is expected | accepted | rejected | accepted | rejected | rejected | rejected | rejected |
|
|
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.
|
|
440
|
+
|
|
441
|
+
To change one Type instead:
|
|
442
|
+
|
|
443
|
+
```ts
|
|
444
|
+
// remove undeclared keys, for this object only
|
|
445
|
+
const Stripped = type({ "+": "delete", name: "string" })
|
|
446
|
+
|
|
447
|
+
// reject them like Joi or Zod's .strict()
|
|
448
|
+
const Strict = type({ "+": "reject", name: "string" })
|
|
449
|
+
|
|
450
|
+
// accept an explicit undefined as well as a missing key
|
|
451
|
+
const Patch = type({ "nickname?": "string | undefined" })
|
|
452
|
+
|
|
453
|
+
// apply a default when the key is missing or undefined
|
|
454
|
+
const Settings = type({
|
|
455
|
+
theme: type("'light' | 'dark' | undefined")
|
|
456
|
+
.pipe(v => v ?? "light")
|
|
457
|
+
.default(undefined)
|
|
458
|
+
})
|
|
459
|
+
|
|
460
|
+
// allow non-finite numbers
|
|
461
|
+
const Measurement = type(
|
|
462
|
+
"number | number.Infinity | number.NegativeInfinity | number.NaN"
|
|
463
|
+
)
|
|
464
|
+
|
|
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
|
|
468
|
+
const Filters = type({ "limit?": "number", "cursor?": "string" }).narrow(
|
|
469
|
+
(o, ctx) => !Array.isArray(o) || ctx.mustBe("an object")
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
// count a string's length in code points, like Zod 4.5's .min(1).max(32)
|
|
473
|
+
const Title = type("string").narrow((s, ctx) => {
|
|
474
|
+
const length = [...s].length
|
|
475
|
+
return (length >= 1 && length <= 32) || ctx.mustBe("1 to 32 characters")
|
|
476
|
+
})
|
|
477
|
+
```
|
|
478
|
+
|
|
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.
|
|
480
|
+
|
|
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()`.
|
|
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
|
+
|
|
485
|
+
## Semantics to check
|
|
486
|
+
|
|
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.
|
|
490
|
+
|
|
491
|
+
```ts
|
|
492
|
+
// Zod: z.string().transform(s => s.length).refine(n => n > 2, "Too short")
|
|
493
|
+
const Length = type("string")
|
|
494
|
+
.pipe(s => s.length)
|
|
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")
|
|
499
|
+
|
|
500
|
+
// Zod: z.preprocess(v => (typeof v === "string" ? v.split(",") : v), z.array(z.string()))
|
|
501
|
+
const Tags = type("string | string[]")
|
|
502
|
+
.pipe(v => (typeof v === "string" ? v.split(",") : v))
|
|
503
|
+
.to("string[]")
|
|
504
|
+
```
|
|
505
|
+
|
|
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()`:
|
|
509
|
+
|
|
510
|
+
```ts
|
|
511
|
+
// z.coerce.number(), which is Number(value) for any input
|
|
512
|
+
const Count = type("unknown").pipe(Number).to("number")
|
|
513
|
+
|
|
514
|
+
// z.coerce.number().int().positive().default(8080) in an object
|
|
515
|
+
const Server = type({
|
|
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)
|
|
521
|
+
})
|
|
522
|
+
|
|
523
|
+
// z.coerce.date(), which is new Date(value) for any input, so null is 1970-01-01
|
|
524
|
+
const When = type("unknown")
|
|
525
|
+
.pipe(
|
|
526
|
+
v => new Date(v instanceof Date || typeof v === "string" ? v : Number(v))
|
|
527
|
+
)
|
|
528
|
+
.to("Date")
|
|
529
|
+
|
|
530
|
+
// stricter, for strings only: rejects " 1", "0x10" and ""
|
|
531
|
+
const Page = type("string.numeric.parse")
|
|
532
|
+
|
|
533
|
+
// z.stringbool() accepts "true", "1", "yes", "on", "y" and "enabled", their
|
|
534
|
+
// opposites, and any casing of them; write the set you need
|
|
535
|
+
const Flag = type("'true' | 'false'").pipe(s => s === "true")
|
|
536
|
+
```
|
|
537
|
+
|
|
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`:
|
|
544
|
+
|
|
545
|
+
```ts
|
|
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"] })
|
|
573
|
+
const Range = type({ start: "number", end: "number" }).narrow(
|
|
574
|
+
(d, ctx) =>
|
|
575
|
+
d.start <= d.end ||
|
|
576
|
+
ctx.reject({
|
|
577
|
+
message: "End must not be before start",
|
|
578
|
+
relativePath: ["end"]
|
|
579
|
+
})
|
|
580
|
+
)
|
|
581
|
+
```
|
|
582
|
+
|
|
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:
|
|
700
|
+
|
|
701
|
+
```ts
|
|
702
|
+
const Count = type("number")
|
|
703
|
+
|
|
704
|
+
// z.object({ count: z.number().catch(0) })
|
|
705
|
+
const Settings = type({
|
|
706
|
+
count: type("unknown")
|
|
707
|
+
.pipe(v => {
|
|
708
|
+
const out = Count(v)
|
|
709
|
+
return out instanceof type.errors ? 0 : out
|
|
710
|
+
})
|
|
711
|
+
.default(0)
|
|
712
|
+
})
|
|
713
|
+
```
|
|
714
|
+
|
|
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
|
|
771
|
+
|
|
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:
|
|
773
|
+
|
|
774
|
+
```ts
|
|
775
|
+
const Category = type({ name: "string", subcategories: "this[]" })
|
|
776
|
+
|
|
777
|
+
const types = scope({
|
|
778
|
+
User: { name: "string", "posts?": "Post[]" },
|
|
779
|
+
Post: { title: "string", author: "User" }
|
|
780
|
+
}).export()
|
|
781
|
+
```
|
|
782
|
+
|
|
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.
|
|
849
|
+
|
|
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.
|
|
851
|
+
|
|
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" })`.
|
|
853
|
+
|
|
854
|
+
### Brands
|
|
855
|
+
|
|
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`.
|
|
857
|
+
|
|
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
|
+
})
|
|
871
|
+
|
|
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.
|
|
985
|
+
|
|
986
|
+
## How to convert
|
|
987
|
+
|
|
988
|
+
1. Write each schema as the TypeScript type it validates. Most constructs become a string or an object definition; this page's tables map them library by library.
|
|
989
|
+
2. Check every row of [Defaults that differ](#defaults-that-differ). A translation that looks right can still accept or return different data.
|
|
990
|
+
3. Confirm the types match. While the old schema still exists, a line like this fails to compile until they do:
|
|
991
|
+
|
|
992
|
+
```ts
|
|
993
|
+
type Equals<a, b> =
|
|
994
|
+
[a] extends [b] ?
|
|
995
|
+
[b] extends [a] ?
|
|
996
|
+
true
|
|
997
|
+
: false
|
|
998
|
+
: false
|
|
999
|
+
const outputMatches: Equals<typeof User.infer, z.output<typeof OldUser>> = true
|
|
1000
|
+
const inputMatches: Equals<typeof User.inferIn, z.input<typeof OldUser>> = true
|
|
1001
|
+
```
|
|
1002
|
+
|
|
1003
|
+
4. Run both on the same inputs, valid and invalid, and compare which they accept and what they return.
|
|
1004
|
+
|
|
1005
|
+
## Adopt incrementally
|
|
1006
|
+
|
|
1007
|
+
You don't have to convert a project at once. ArkType and Zod both implement [Standard Schema](https://arktype.io/docs/standard-schema), so each can stand in for the other while you convert:
|
|
1008
|
+
|
|
1009
|
+
- **A Zod schema works inside an ArkType definition**, so convert the schemas that use it first and the shared one later:
|
|
1010
|
+
|
|
1011
|
+
```ts
|
|
1012
|
+
import { z } from "zod"
|
|
1013
|
+
|
|
1014
|
+
// not converted yet
|
|
1015
|
+
const Address = z.object({ street: z.string(), city: z.string() })
|
|
1016
|
+
|
|
1017
|
+
const User = type({ name: "string", address: Address })
|
|
1018
|
+
```
|
|
1019
|
+
|
|
1020
|
+
- **An ArkType Type works wherever a library accepts Standard Schema**, like tRPC, TanStack Form, Hono's `sValidator` or react-hook-form's `standardSchemaResolver`, so call sites can switch one at a time. [Swap integrations](#migrating-a-project) has each.
|
|
1021
|
+
|
|
1022
|
+
A Valibot schema embeds the same way. Yup's validates asynchronously, so it can't.
|
|
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
|
+
|
|
1026
|
+
## Precompile
|
|
1027
|
+
|
|
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.
|
|
1029
|
+
|
|
1030
|
+
A definition that still embeds a Zod or Valibot schema can't be precompiled yet, so the build fails, naming it. Until you've converted it, build with `runtime: "arktype"`, which ships arktype, so what the build can't precompile runs as it did before:
|
|
1031
|
+
|
|
1032
|
+
```ts
|
|
1033
|
+
import { precompile } from "@ark/aot/unplugin"
|
|
1034
|
+
import { defineConfig } from "vite"
|
|
1035
|
+
|
|
1036
|
+
export default defineConfig({
|
|
1037
|
+
plugins: [precompile.vite({ runtime: "arktype" })]
|
|
1038
|
+
})
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
To see what's left, run `npx arktype-precompile --check`, which lists each definition the default build would refuse. See [Dynamic vs Precompiled](https://arktype.io/docs/precompile/dynamic-vs-precompiled).
|
|
1042
|
+
|
|
1043
|
+
`drizzle-arktype`, from [Swap integrations](#migrating-a-project), creates Types from your tables as the program runs, so the build [runs it on arktype](https://arktype.io/docs/precompile/options#dependencies), shipping the parser. To precompile those Types too, write each one out, with a line that fails to compile if it drifts from the table, like `const matches: Equals<typeof selectTask.infer, typeof tasks.$inferSelect> = true`, `Equals` as in [How to convert](#how-to-convert).
|
|
1044
|
+
|
|
1045
|
+
## Valibot
|
|
1046
|
+
|
|
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.
|
|
1083
|
+
|
|
1084
|
+
## TypeBox
|
|
1085
|
+
|
|
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` |
|
|
1111
|
+
|
|
1112
|
+
## Yup
|
|
1113
|
+
|
|
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.
|
|
1121
|
+
|
|
1122
|
+
| Yup | ArkType |
|
|
1123
|
+
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1124
|
+
| `object({...})`, `.shape({...})` | `type({...})`, `.merge({...})` |
|
|
1125
|
+
| `string()` (not required) | `"key?": "string \| undefined"` |
|
|
1126
|
+
| `.required()`, `.defined()`, `.nullable()` | `"key": "string > 0"` for strings, `"key": "T"`, `"T \| null"` |
|
|
1127
|
+
| `.default(x)` | `"key": "T = x"` |
|
|
1128
|
+
| `.email()`, `.url()`, `.uuid()`, `.matches(r)` | `"string.email"`, `"string.url"`, `"string.uuid"`, `/r/` |
|
|
1129
|
+
| `.min(n)`, `.max(n)`, `.length(n)` on strings, arrays | `"string >= n"`, `"T[] <= n"`, `"string == n"` |
|
|
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")` |
|
|
1134
|
+
| `.trim()`, `.lowercase()` | `"string.trim"`, `"string.lower"` |
|
|
1135
|
+
| `.oneOf(["a", "b"])` | `"'a' \| 'b'"` |
|
|
1136
|
+
| `array().of(T)`, `tuple([A, B])` | `T.array()`, `[A, B]` |
|
|
1137
|
+
| `.test(name, message, fn)` | `.narrow((x, ctx) => fn(x) \|\| ctx.reject({ message }))` |
|
|
1138
|
+
| `.oneOf([ref("password")])` | a `.narrow()` on the object comparing the keys, which runs only once every key is valid, where Yup reports the mismatch beside other errors |
|
|
1139
|
+
| `.transform(fn)` | `.pipe(fn)` |
|
|
1140
|
+
| `.when("other", ...)` | a union of the cases, or a `.narrow()` on the object |
|
|
1141
|
+
| `lazy` | a scope or `this` |
|
|
1142
|
+
| `.noUnknown()`, `stripUnknown: true` | `"+": "delete"` for both, since `.noUnknown()` removes the keys too, and `"+": "reject"` where it's validated with `strict: true` |
|
|
1143
|
+
| `InferType<typeof S>` | `typeof T.infer` |
|
|
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
|
+
```
|
|
1186
|
+
|
|
1187
|
+
## Joi
|
|
1188
|
+
|
|
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)` |
|
|
1218
|
+
|
|
1219
|
+
## Effect Schema
|
|
1220
|
+
|
|
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"` |
|
|
1263
|
+
|
|
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.
|
|
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
|
+
|
|
1268
|
+
## JSON Schema and ajv
|
|
1269
|
+
|
|
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:
|
|
1271
|
+
|
|
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).
|
|
1295
|
+
|
|
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.
|