Show HN:ArkType 3.0 —— 基于集合论的预编译 TS 校验器
Show HN: ArkType 3.0 – Set-theoretic precompiled TS validator

原始链接: https://arktype.io/docs/blog/3.0

ArkType 3.0 现已正式发布,定位为体积最小、速度最快、上手最快的 TypeScript 验证器。其最大变化是预编译:借助 @ark/aot,每个 Type 都会在构建时变成一个独立的验证器,而无需更改 schema 定义或推断类型。团队报告称,预编译后的 ArkType 在全部 32 个基准场景中都胜过 Zod 4(中位数 15 倍),并比 Zod 4 的编译模式快 5.3 倍,同时在启动时间和打包体积基准上平均领先;不过 AJV 在某些无效数据错误场景中更快。 从 Zod 迁移可通过一项智能体技能完成:npx skills add arktypeio/arktype,然后提示智能体转换 schema、保留错误信息与集成、运行类型检查/测试,并将未覆盖的 schema 与 Zod 对比。ArkType 的 Type 都是带有 JSON Schema 输出的 Standard Schema,因此 tRPC、TanStack Form、AI SDK 和 MCP SDK 等库都可以使用它们。由于 Zod schema 可以放在 ArkType 定义中,因此支持增量迁移。 ArkType 还将集合论归一化移到构建阶段:联合类型会获得判别器,冗余检查会消失,矛盾会导致构建失败。代价是需要一个构建步骤;纯运行时定义需要“运行时孤岛”或完整运行时。动态模式仍然可用。

ArkType 3.0 推出了 `@ark/aot`,这是其 TypeScript 验证库的一个可选的提前编译步骤。作者表示,智能体开发使构建时优化更加实用,而 ArkType 的集合论类型系统现在能够生成 JavaScript 验证器;据称,与 Zod 4 相比,这些验证器的验证速度快 15 倍、打包体积小 21 倍、启动速度快 63 倍。作者称,AI 智能体通常能一次完成迁移,并欢迎反馈或提问。
相关文章

原文

As of today, ArkType 3.0 is generally available 🎉

Fast, small, quick to start: validators have always made you pick 2. Ask around and you'd hear ArkType for speed, Valibot for size and Typia if you can live with a build step.

We recently asked which of the three you care about most. Trick question.

Pick 3.

TypeScript's smallest, fastest validator. Quickest to start, too. How we measured ↓

  • What's new: ArkType precompiles. One plugin turns each Type into a standalone validator when you build, and your definitions don't change.
  • Against Zod: Precompiled ArkType was faster than Zod 4 in all 32 scenarios of our benchmark, by a median of 15×, and faster than Zod 4's z.compile in 32 of 32, by a median of 5.3×. Startup and size are below.
  • What switching costs: one command and one prompt. Your schemas keep their names, their messages and the libraries that read them. What doesn't carry over is listed too.

If speed was never your issue, fair: ArkType was always about the DX. Definitions read like the types you'd write anyway, tsc checks them as you type and errors say what went wrong.

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

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

Precompiled, your definitions and the types they infer don't change. You just stop paying for them in speed, startup or size.

Switching from Zod

Add the skill:

npx skills add arktypeio/arktype

Then ask your agent:

Migrate this project from Zod to ArkType.

Migrate from Zod with one prompt: your agent converts each schema where it is, then checks its work with your typecheck and tests. Before it removes zod, it runs each schema your tests don't cover against its Zod original on the same inputs. Where a dependency accepts only Zod, like MCP SDK v1, it keeps Zod for that call and tells you. Add "and precompile it" to do both in one pass.

A schema before:

import { z } from "zod"

const Signup = z.object({
	email: z.email("Enter a valid email"),
	password: z.string().min(8, "Use 8 or more characters"),
	role: z.enum(["admin", "member"])
})

type Signup = z.infer<typeof Signup>

And after:

import { type } from "arktype"

const Signup = type({
	email: type("string.email").message("Enter a valid email"),
	password: type.string.atLeastLength(8, "Use 8 or more characters"),
	role: "'admin' | 'member'"
})

type Signup = typeof Signup.infer

Your agent sets onUndeclaredKey: "delete" once, so objects keep removing undeclared keys as z.object() does.

Your messages work the way they did in Zod

A message is shown exactly as you wrote it and never includes its path, as Zod's issue.message doesn't. summary writes the path before it for a log:

const out = Signup({ email: "x", password: "short", role: "admin" })

if (out instanceof type.errors) {
	// ["Enter a valid email", "Use 8 or more characters"]
	out.issues.map(issue => issue.message)
	// email: Enter a valid email
	// password: Use 8 or more characters
	out.summary
}

// what a form library reads: the paths and messages the Zod schema returns
Signup["~standard"].validate({ email: "x", password: "short", role: "admin" })
// { issues: [
//     { path: ["email"], message: "Enter a valid email", ... },
//     { path: ["password"], message: "Use 8 or more characters", ... }
// ] }

A missing key says its value's message too, so it's the required_error as well, and .label() names a field in every built-in message without writing a custom message per check. A .refine()'s message becomes ctx.reject({ message, relativePath }) in a .narrow().

Your libraries take the Type as they took the schema

Every Type is a Standard Schema that writes its own JSON Schema. tRPC, TanStack Form and @t3-oss/env take it in the same call, react-hook-form takes it through standardSchemaResolver, and the AI SDK from v6 and the MCP SDK from v2 take it as a tool's inputSchema. Swap integrations lists each library's change, where there is one.

You don't have to finish

A Zod schema works inside an ArkType definition, so you can convert one file at a time and leave shared schemas for last:

import { z } from "zod"

// not converted yet
const Address = z.object({ street: z.string(), city: z.string() })

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

Or start without switching

fromJsonSchema runs ArkType's set theory on the Zod schemas and JSON Schemas you already have. In CI, .extends() tells you whether a change to an API schema still accepts everything the old one did:

import { fromJsonSchema } from "arktype"
import { z } from "zod"

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

// v2 accepts everything v1 did, so the change is backwards compatible
v1.extends(v2) // true
// but not the other way around: v2 accepts { id: "a" }
v2.extends(v1) // false

It reads a schema from Zod 4.2 or later as the JSON Schema it writes, which leaves out refinements and transforms.

What a migration has to handle

The guide your agent follows maps each Zod API and covers each of these, and its summary lists anything it couldn't keep identical.

  • Defaults differ. Besides undeclared keys, Zod's .optional() accepts undefined, where ArkType reads an optional key as TypeScript's exactOptionalPropertyTypes does, so the migration configures exactOptionalPropertyTypes: false and writes "key?": "T". Defaults that differ has every row.
  • Validation is synchronous. An async .refine() moves out of the schema, to run after validation.
  • A check across keys runs last. A .narrow() on an object runs once every key is valid, where Zod 4 also runs a .refine() when a key fails a check like .min(). A form shows Passwords must match once its fields pass.
  • Default messages are ArkType's, like must be an email address where Zod says Invalid email address. Messages you wrote don't change.

Agents don't mind a build step

When 2.0 launched, we bragged that it needed no build step. That was the right call then: precompiled validators were always faster and smaller, but they cost a plugin to set up, errors you'd never seen and a second model of what runs where.

Then agents started doing the setup. An agent adds the plugin, reads the errors and fixes what they point to, and shadow mode runs your tests against both models, failing wherever they disagree. What's left is the time a build takes, while your users still download everything you ship, our parser included.

So ArkType precompiles, and every message along the way names the fix.

Definitions are checked by tsc as you write them, and a typo's error suggests the fix:

const User = type({
	id: "number | strin"

TypeScript: "number | string"

})

The build reports what it can't precompile with the file, line, reason and fix. Usually, it's a definition built from a value known only at runtime:

src/forms.ts:14:19  type(`string <= ${limit}`) cannot be precompiled
  `limit` is a parameter of makeField (src/forms.ts:12:22); its value is known only at runtime
  Write the definition where makeField is called, with the value it passes for `limit`, so the build precompiles each call.

Validation returns errors that say where and what was expected, ready to hand back to a model as a tool result.

Troubleshooting quotes each message the build can report.

Setup is the plugin, or ark emit after tsc where there's no bundler:

import { precompile } from "@ark/aot/unplugin"

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

npx arktype check "src/**/*.ts" lists every definition the build would refuse before you switch.

Dynamic, like always

type() still parses definitions at runtime with no build step, for scripts, REPLs and definitions you only know at runtime. In a precompiled build, a runtime island leaves one definition to arktype and runtime: "arktype" ships arktype whole, so nothing you write today keeps you from precompiling.

The skill

An agent's training always lags a release. npx skills add arktypeio/arktype adds the skill, which teaches it current syntax, how it maps to TypeScript, the mistakes to avoid and how to work in a precompiled project. Every docs page is also Markdown at its URL plus .md, and /llms.txt indexes them.

What it costs

  • A build step: the plugin, set up once, and the time each build takes.
  • Definitions known only at runtime fail a standalone build. Keep them dynamic as runtime islands, or build with runtime: "arktype".
  • A standalone validator validates, asserts and is a Standard Schema, but doesn't compose or introspect at runtime and has no locales. runtime: "arktype" keeps the whole Type API.
  • Without the plugin: Dynamic ArkType is 98.1 kB gzipped, minified with esbuild, up from 47.8 kB in 2.2.9, so precompile to ship less.

If you're upgrading from 2.2, Upgrading lists what breaks.

The numbers

  • ⚡ Fastest on average across 22 results from 2 independent benchmarks: 658 CPU instructions per validation against Typia's 2,097, 68.6% lower.
  • 🧊 On each of the 4 apps in our startup benchmark, precompiled ArkType's default build ran fewer instructions from import through its first validation than every other library measured on it (Valibot, Zod, Zod (compiled), Zod Mini, Typia, ajv and TypeBox), by 23.8% or more, in at least 17 of 20 paired runs on Node 24.
  • 📦 Smallest on average across valibot.dev's login form and schemabenchmarks.dev's download: 1.19 kB gzipped against Typia's 1.52 kB, 21.7% lower.

Ranked by geometric mean across other projects' public benchmarks and valibot.dev's login form, which we wrote in each library from Valibot's code: 22 results for validation speed, 2 for startup and 2 for bundle size; the 2 startup results time creating a schema. Each category averages the largest set of results that ArkType, Zod and three more named libraries all ran, in the unit they measure, and ranks every library that ran all of them, in plain order. ArkType is its default precompiled build in all three. We name only libraries with 100k+ npm downloads a week; every place and average counts all of them. A monthly job reruns the size benchmarks at each library's newest release.

Precompiled ArkType was faster than Zod 4 in all 32 scenarios of our benchmark, by a median of 15×, and faster than Zod 4's z.compile in 32 of 32, by a median of 5.3×. It isn't the fastest at everything. On the rows that report errors for invalid data, ajv was faster on 8 of 15.

Benchmarks has how each was measured, who wrote it and where the numbers stop holding.

@ark/aot

@ark/aot is a plugin for Vite, Rollup, Rolldown, webpack, Rspack, esbuild, Bun and Farm, and Vitest runs tests through it. Drivers cover Node, Bun's runtime and Next's Turbopack. Setup has a config for each.

Each Type your program defines becomes a validator that imports only arktype/runtime, and code that calls it doesn't change. Scopes, Modules, Generics, cyclic Types, match and type.fn precompile too.

Options go in an ark.json that the plugin, the drivers, the CLI and the ESLint rule all read. Build the fastest validator or the smallest from the same definitions. The "smallest" preset trades speed for size. A library opts in with "ark": { "aot": true } in its package.json, so its consumers' builds precompile it.

Set theory at build time

ArkType reduces every definition to a normalized set of constraints, so it knows which Types overlap, which are subtypes of others and which can never both be satisfied. Precompiled, all of that happens in your build:

  • Unions discriminate themselves. ArkType finds the key that tells a union's branches apart and switches on it, and a branch never rechecks the key it was chosen by. You never declare a discriminator.
  • Redundant checks disappear. number > 0 intersected with number >= 10 is one check, number >= 10.
  • Contradictions never ship. { id: string } intersected with { id: number } throws a ParseError, which fails the build rather than shipping a validator that rejects everything.

Edit the definition, and the precompiler runs on what you type:

1write a Typeshape.ts
const Shape = type({
	kind: "'circle'",
	radius: "number > 0"
}).or({
	kind: "'square'",
	side: "number > 0"
})
the real precompiler runs in this tab

@ark/aot ↓

2what shipsas emitted · names shortened
const check1 = function (data, ctx) {	switch(data?.kind) {		case "circle": return check2(data)		case "square": return check3(data)	}	return false}
3 helpers
const check2 = function (data, ctx) {	for (;;) {		if (!((check4(data.radius)))) {			break		}		return true	}	return false}
const check3 = function (data, ctx) {	for (;;) {		if (!((check4(data.side)))) {			break		}		return true	}	return false}
const check4 = function (data, ctx) {	return (Number.isFinite(data)) && (data > 0)}
7 lines + 3 helpers · no parser, no new Functionerror path and wiring not shown

ArkType isn't the first validator to compile. Typia also generates checks from your TypeScript types at build time, and it specializes some unions. The difference is that ArkType normalizes your constraints with its own set theory, so definitions are reduced, intersected and discriminated before any code is written.

codec and .encode

codec pairs a morph with its inverse, and every Type's .encode inverts each of its morphs, so a codec encodes wherever it's nested:

import { codec } from "arktype/codecs"

const EpochMs = codec("number.integer", "Date", {
	decode: n => new Date(n),
	encode: d => d.getTime()
})

const Event = type({ name: "string", at: EpochMs })

// { name: "launch", at: new Date(0) }
const event = Event({ name: "launch", at: 0 })
// { name: "launch", at: 0 }
const encoded = Event.encode(event)

Parse keywords like string.date.iso.parse encode back to strings, and codecs precompile like any other definition. See Codecs.

Everything else

  • number rejects Infinity: as it already rejected NaN. numberAllowsInfinity allows it everywhere.
  • Error messages in other languages: a locale writes validation errors in another language, with dynamic Types or runtime: "arktype". ArkType ships en and de, and a locale is an object you can spread, extend or write from scratch.
  • Fewer errors: errors "first" stops at the first error, and "none" returns one saying the data is invalid. mutatesInput writes what a Type transforms into its input instead of copying it. Each is installed by its own import, so a program that doesn't choose one doesn't ship it.
  • Dynamic Types do less work: a Type compiles when it's first used, and one without narrows or morphs finds its errors' issues only when they're first read. Dynamic ArkType validates moltar's strict cases about 10 times faster than 2.2.
  • Syntax and scopes: != excludes one value, unions of ranges merge where they can, an object's "@" key holds its description or meta, string.nonblank and string.url.http cover common form fields, and ambient lets a scope override or opt out of default keywords for DSLs.
  • Compare any schemas: fromJsonSchema reads a Standard JSON Schema like Zod's or plain JSON Schema into a Type, so .extends(), .equals() and .overlaps() relate them, as above, with each other and with your Types, and .and(), .or() and .toJsonSchema() combine and convert them.
  • JSON Schema: every Type is a Standard Schema that writes its own JSON Schema, and a precompiled one keeps it where its build sees code read it, so the MCP SDK, the AI SDK and OpenAPI generators get it with nothing to set. toJsonSchema writes draft 2020-12, draft-07, OpenAPI 3.0 or OpenAPI 3.1, and fromJsonSchema reads one back as a Type.
  • Errors as data: an ArkErrors' issues are plain objects discriminated by code. An issue's message leaves out its path, which summary writes before it, and one you configure is shown as you wrote it. ArkType's own English messages don't print the value, so they don't put what the data holds into a log.
  • More editors: JetBrains IDEs, Neovim and Helix join VS Code today, with the Zed extension awaiting marketplace review, all tested against the VS Code extension's fixtures.
  • A new home: every docs page reads as Markdown for your agent, every code sample shows the types TypeScript infers, and the playground runs the real parser in your browser.

Upgrading lists each breaking change with what to write instead, and the CHANGELOGs of arktype, @ark/aot, @ark/fast-check, arkregex and @ark/attest have the rest.

⚡ Start coding

⭐ Check out the project on GitHub

👋 Join our Discord to lurk or ask questions

  • Follow any of these accounts for updates:

  • Consider supporting my work on ArkType via GitHub Sponsors

联系我们 contact @ memedata.com