llms.txt
Compare with other sites' llms.txt files →# ArkType
> TypeScript's 1:1 validator
# Setup
## Installation
```bash
npm install arktype
```
You'll also need...
- TypeScript version `>=5.1`.
- A `package.json` with `"type": "module"` (or an environment that supports ESM imports)
- A `tsconfig.json` with...
- [`strict`](https://www.typescriptlang.org/tsconfig#strict) or [`strictNullChecks`](https://www.typescriptlang.org/tsconfig#strictNullChecks) (**required**)
- [`skipLibCheck`](https://www.typescriptlang.org/tsconfig#skipLibCheck) (strongly recommended, see [FAQ](https://arktype.io/docs/faq#why-do-i-see-type-errors-in-an-arktype-package-in-node_modules))
- [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes) (recommended)
## VSCode
### Settings
To take advantage of all of ArkType's autocomplete capabilities, you'll need to add the following to your workspace settings at `.vscode/settings.json`:
```json
// allow autocomplete for ArkType expressions like "string | num"
"editor.quickSuggestions": {
"strings": "on"
},
// prioritize ArkType's "type" for autoimports
"typescript.preferences.autoImportSpecifierExcludeRegexes": [
"^(node:)?os$"
],
```
### Extension (optional)
[ArkDark](https://marketplace.visualstudio.com/items?itemName=arktypeio.arkdark) provides the embedded syntax highlighting you'll see throughout the docs.
Without it, your definitions can still feel like a natural extension of the language.
With it, you'll forget there was ever a boundary in the first place.
## JetBrains IDEs
### Extension (optional)
[ArkType](https://plugins.jetbrains.com/plugin/27099-arktype) provides the embedded syntax highlighting you are familiar with for typescript types.
## Other editors
If you're using a different editor, we'd love [help adding support](https://github.com/arktypeio/arktype/issues/989). In the meantime, don't worry- ArkType still offers best-in-class DX anywhere TypeScript is supported.
# Your First Type
If you already know TypeScript, congratulations- you just learned most of ArkType's syntax 🎉
## Define
```ts
import { type } from "arktype"
const User = type({
name: "string",
platform: "'android' | 'ios'",
"versions?": "(number | string)[]"
})
// extract the type if needed
type User = typeof User.infer
```
If you make a mistake, don't worry- every definition gets the autocomplete and validation you're used to from your editor, all within TypeScript's type system.
> **Will ArkType crash my TypeScript server?**
>
> Thousands of hours of optimization have gone into making validating native
> type syntax not just feasible, but often much faster than alternatives ⚡
## Compose
Suppose we want to move `platform` and `versions` from our original type to a new `device` property.
```ts
const User = type({
name: "string",
// nested definitions don't need to be wrapped
device: {
platform: "'android' | 'ios'",
"versions?": "(number | string)[]"
}
})
```
To decouple `device` from `User`, just move it to its own type and reference it.
```ts
const Device = type({
platform: "'android' | 'ios'",
"versions?": "(number | string)[]"
})
const User = type({
name: "string",
device: Device
})
```
## Validate
At runtime, we can pass `unknown` data to our type and get back either a validated `User` or an array of clear, customizable errors with a root `summary`.
```ts
const out = User({
name: "Alan Turing",
device: {
platform: "enigma",
versions: [0, "1", 0n]
}
})
if (out instanceof type.errors) {
// hover out.summary to see validation errors
console.error(out.summary)
} else {
// hover out to see your validated data
console.log(`Hello, ${out.name}`)
}
```
And that's it! You now know how to define a `Type` and use it to check your data at runtime.
Next, we'll take a look at how ArkType extends TypeScript's type system to handle runtime constraints like `maxLength` and `pattern`.
# Adding Constraints
TypeScript is extremely versatile for representing types like `string` or `number`, but what about `email` or `integer less than 100`?
In ArkType, conditions that narrow a type beyond its **basis** are called **constraints**.
Constraints are a first-class citizen of ArkType. They are fully composable with TypeScript's built-in operators and governed by the same underlying principles of set-theory.
## Define
Let's create a new `contact` Type that enforces our example constraints.
```ts
const Contact = type({
// many common constraints are available as built-in keywords
email: "string.email",
// others can be written as type-safe expressions
score: "number.integer < 100"
})
// if you need the TS type, just infer it out as normal
type Contact = typeof Contact.infer
```
## Compose
Imagine we want to define a new Type representing a non-empty list of `Contact`.
While the expression syntax we've been using is ideal for creating new types, chaining is a great way to refine or transform existing ones.
```ts
const _Contact = type({
email: "string.email",
score: "number.integer < 100"
})
type _Contact = typeof _Contact.t
interface Contact extends _Contact {}
export const Contact: type<Contact> = _Contact
const Contacts = Contact.array().atLeastLength(1)
```
## Narrow
Structured constraints like divisors and ranges will only take us so far. Luckily, they integrate seamlessly with whatever custom validation logic you need.
```ts
// there's no "not divisible" expression - need to narrow
const Odd = type("number").narrow((n, ctx) =>
// if even, add a customizable error and return false
n % 2 === 0 ? ctx.mustBe("odd") : true
)
const FavoriteNumbers = type({
even: "number % 2",
odd: Odd
})
const out = FavoriteNumbers({
even: 7,
odd: 8
})
if (out instanceof type.errors) {
// hover summary to see validation errors
console.error(out.summary)
} else {
console.log(out.odd)
}
```
You now know how to refine your types to enforce additional constraints at runtime.
But what if once your input is fully validated, you still need to make some adjustments before it's ready to use?
The final section of intro will cover **morphs**, an extremely powerful tool for composing and transforming Types.
# Morphs & More
Sometimes, data at the boundaries of your code requires more than validation before it's ready to use.
**Morphs** allow you to arbitrarily transform the shape and format of your data.
Morphs can be **piped** before, after or between validators and even chained to other morphs.
```ts
// Hover to see the type-level representation
const parseJson = type("string").pipe((s): object => JSON.parse(s))
// object: { ark: "type" }
const out = parseJson('{ "ark": "type" }')
// ArkErrors: must be a string (was object)
const badOut = parseJson(out)
```
This is a good start, but there are still a couple major issues with our morph.
What happens if we pass a string that isn't valid JSON?
```ts
// Uncaught SyntaxError: Expected property name ☠️
const badOut = parseJson('{ unquoted: "keys" }')
```
Despite what `JSON.parse` might have you believe, throwing exceptions and returning `any` are not very good ways to parse a string. By default, ArkType assumes that if one of your morphs or narrows throws, you intend to crash.
If you do happen to find yourself at the mercy of an unsafe API, you might consider wrapping your function body in a `try...catch`.
Luckily, there is a built-in API for wrapping `pipe`d functions you don't trust:
```ts
const parseJson = type("string").pipe.try((s): object => JSON.parse(s))
// Now returns an introspectable error instead of crashing 🎉
const badOut = parseJson('{ unquoted: "keys" }')
const out = parseJson('{ "ark": "type" }')
if (out instanceof type.errors) out.throw()
// Unfortunately, a validated `object` still isn't very useful...
else console.log(out)
```
The best part about `pipe` is that since any `Type` is root-invokable, `Type`s themselves _are_ already morphs! This means validating out parsed output is as easy as adding another pipe:
```ts
const parseJson = type("string").pipe.try(
(s): object => JSON.parse(s),
type({
name: "string",
version: "string.semver"
})
)
const out = parseJson('{ "name": "arktype", "version": "2.0.0" }')
if (!(out instanceof type.errors)) {
// Logs "arktype:2.0.0"
console.log(`${out.name}:${out.version}`)
}
```
At this point, our implementation is starting to look pretty clean, but in many cases like this one, we can skip straight to the punch line with one of ArkType's many built-in aliases for validation and parsing, `string.json.parse`:
```ts
// .to is a sugared .pipe for a single parsed output validator
const parseJson = type("string.json.parse").to({
name: "string",
version: "string.semver"
})
const out = parseJson('{ "name": true, "version": "v2.0.0" }')
if (out instanceof type.errors) {
// hover out.summary to see the default error message
console.error(out.summary)
}
```
If you've made it this far, congratulations! You should have all the fundamental intuitions you need to bring your types to runtime ⛵
Our remaining docs will help you understand the trade offs between ArkType's most important APIs so that no matter the application, you can find a solution that feels great to write, great to read, and great to run.
# Cheat Sheet
A quick reference for ArkType's most common patterns. For full docs, explore the sidebar.
## Syntax Kinds
ArkType offers three ways to define the same type. Use whichever fits your context.
```ts
import { type } from "arktype"
// string expression — most concise
const StringSyntax = type("string | number")
// tuple expression — embed non-string operands
const TupleSyntax = type(["string", "|", "number"])
// chained — compose existing types
const Chained = type("string").or("number")
```
## Keywords
Keywords follow a `typescriptType.constraint.subconstraint` pattern:
```ts
// string keywords
type("string.email") // email format
type("string.uuid") // UUID format
type("string.url") // parsable URL
type("string.trim") // morph: trims whitespace
type("string.json.parse") // morph: string → parsed JSON
type("string.date.parse") // morph: string → Date
// number keywords
type("number.integer") // whole numbers
type("number.safe") // within safe integer range
type("number.epoch") // valid Unix timestamp
```
## Operators
```ts
type("string | number") // union
type("string & /@foo/") // intersection
type("number > 0") // exclusive min
type("number >= 0") // inclusive min
type("string <= 255") // max length
// defaults — valid inside objects (key becomes implicitly optional)
type({ email: "string.email = 'n/a'" })
```
## Objects
```ts
const User = type({
name: "string",
"email?": "string.email", // optional key — use '?' suffix in the key
age: "number >= 0 = 0" // default value — implicitly optional
})
// index signatures (Record types)
const Env = type({
"[string]": "string" // Record<string, string>
})
// strip undeclared keys
const Strict = User.onUndeclaredKey("delete")
```
## Arrays and Tuples
```ts
const Strings = type("string[]") // string expression
const Numbers = type.number.array() // chained
// tuples — fixed length and positional types
const Pair = type(["string", "number"])
// GOTCHA: type([X]) is a 1-element tuple, NOT an array
const Item = type({ id: "string" })
const Wrong = type([Item]) // tuple of exactly [Item]
const Right = Item.array() // Item[]
// readonly
const Ids = type("string[]").readonly() // readonly string[]
```
## Composition
```ts
const Device = type({
platform: "'android' | 'ios'",
"version?": "string"
})
// reference in another type — just pass it directly
const User = type({
name: "string",
device: Device
})
// fluent composition
const Admin = User.and({ role: "'admin'" })
const Guest = type({ name: "string" }).or({ token: "string" })
```
## Morphs and Pipes
```ts
// .to() — validated input → validated output
const ParsedInt = type("string").to("number.integer")
// .pipe() — validated input → transform function
const ToUpper = type("string").pipe(s => s.toUpperCase())
// built-in parse morphs
const ParseDate = type("string.date.parse") // string → Date
const ParseJson = type("string.json.parse") // string → object
const Trimmed = type("string.trim") // string → trimmed string
```
## Type Inference
```ts
const User = type({
name: "string",
"age?": "number"
})
// extract the TypeScript type
type User = typeof User.infer
// { name: string; age?: number }
```
## Error Handling
```ts
const User = type({
name: "string",
"age?": "number"
})
const out = User({ name: "Alan", age: "not a number" })
if (out instanceof type.errors) {
// ArkErrors — array-like with .summary
console.error(out.summary)
} else {
// out is typed as { name: string; age?: number }
console.log(out.name)
}
```
## Common Gotchas
| Mistake | Fix |
| ------------------------------------------ | ----------------------------------------------------------- |
| `name: "string \| undefined"` for optional | Use `"name?": "string"` — append `?` to the **key** |
| `type([Schema])` for arrays | Use `Schema.array()` — brackets create tuples |
| `"Record<string, T>"` with `T` a variable | Use `type.Record("string", T)` or `{ "[string]": T }` |
| Manually re-validating after `type()` | Trust ArkType's output — it already validated the structure |
| `type User = typeof Schema.t` | Use `typeof Schema.infer` for the output type |
# Agents
> Help Claude Code, Codex, Cursor and other coding agents write ArkType
## Skill
The ArkType skill tells agents when to reach for ArkType, how its syntax maps to TypeScript, and which mistakes to avoid. Add it to your project with:
```bash
npx skills add arktypeio/arktype
```
Releases after 2.2.8 also include the skill in the `arktype` package at `skills/arktype/SKILL.md`, so tools like [skills-npm](https://github.com/antfu/skills-npm) can link the copy that matches your installed version.
## Docs as Markdown
Every page of these docs is available as Markdown by adding `.md` to its URL, e.g. [/docs/intro/setup.md](https://arktype.io/docs/intro/setup.md). The buttons under each page's title copy it or open it in Claude, ChatGPT or Cursor.
[/llms.txt](https://arktype.io/llms.txt) has every ArkType page in one file, in the order of the sidebar. Attest's docs are at [/docs/attest/llms.txt](https://arktype.io/docs/attest/llms.txt).
## AGENTS.md
If your project has an `AGENTS.md` or `CLAUDE.md`, a line like this keeps agents on ArkType when they add validation:
```
Validate untrusted input with ArkType. Docs: https://arktype.io/llms.txt
```
# Primitives
## string
### keywords
The following keywords can be referenced in any definition, e.g.:
```ts
const Email = type("string.email")
const User = type({
data: "string.json.parse",
ids: "string.uuid.v4[]"
})
```
| Alias | Description |
| --- | --- |
| `string` | a string |
| `string.alpha` | only letters |
| `string.alphanumeric` | only letters and digits 0-9 |
| `string.base58` | base58-encoded |
| `string.base64` | base64-encoded |
| `string.base64.url` | base64url-encoded |
| `string.capitalize` | a morph from a string to capitalized |
| `string.capitalize.preformatted` | capitalized |
| `string.creditCard` | a credit card number and a credit card number |
| `string.date` | a string and a parsable date |
| `string.date.epoch` | an integer string representing a safe Unix timestamp |
| `string.date.epoch.parse` | a morph from an integer string representing a safe Unix timestamp to a Date |
| `string.date.iso` | an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date |
| `string.date.iso.parse` | a morph from an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date to a Date |
| `string.date.parse` | a morph from a string and a parsable date to a Date |
| `string.digits` | only digits 0-9 |
| `string.email` | an email address |
| `string.hex` | hex characters only |
| `string.integer` | a well-formed integer string |
| `string.integer.parse` | a morph from a well-formed integer string to an integer |
| `string.ip` | an IP address |
| `string.ip.v4` | an IPv4 address |
| `string.ip.v6` | an IPv6 address |
| `string.json` | a JSON string |
| `string.json.parse` | safe JSON string parser |
| `string.lower` | a morph from a string to only lowercase letters |
| `string.lower.preformatted` | only lowercase letters |
| `string.normalize` | a morph from a string to NFC-normalized unicode |
| `string.normalize.NFC` | a morph from a string to NFC-normalized unicode |
| `string.normalize.NFC.preformatted` | NFC-normalized unicode |
| `string.normalize.NFD` | a morph from a string to NFD-normalized unicode |
| `string.normalize.NFD.preformatted` | NFD-normalized unicode |
| `string.normalize.NFKC` | a morph from a string to NFKC-normalized unicode |
| `string.normalize.NFKC.preformatted` | NFKC-normalized unicode |
| `string.normalize.NFKD` | a morph from a string to NFKD-normalized unicode |
| `string.normalize.NFKD.preformatted` | NFKD-normalized unicode |
| `string.numeric` | a well-formed numeric string |
| `string.numeric.parse` | a morph from a well-formed numeric string to a number |
| `string.regex` | a string and a regex pattern |
| `string.semver` | a semantic version (see https://semver.org/) |
| `string.trim` | a morph from a string to trimmed |
| `string.trim.preformatted` | trimmed |
| `string.upper` | a morph from a string to only uppercase letters |
| `string.upper.preformatted` | only uppercase letters |
| `string.url` | a string and a URL string |
| `string.url.parse` | a morph from a string and a URL string to a URL instance |
| `string.uuid` | a UUID |
| `string.uuid.v1` | a UUIDv1 |
| `string.uuid.v2` | a UUIDv2 |
| `string.uuid.v3` | a UUIDv3 |
| `string.uuid.v4` | a UUIDv4 |
| `string.uuid.v5` | a UUIDv5 |
| `string.uuid.v6` | a UUIDv6 |
| `string.uuid.v7` | a UUIDv7 |
| `string.uuid.v8` | a UUIDv8 |
### literals
```ts
const Literals = type({
singleQuoted: "'typescript'",
doubleQuoted: '"arktype"'
})
```
### patterns
Regex literals specify an unanchored regular expression that an input string must match.
They can either be string-embedded or refer directly to a `RegExp` instance.
```ts
const Literals = type({
stringEmbedded: "/^a.*z$/",
regexLiteral: /^a.*z$/
})
```
Regex literals now carry full type inference via [arkregex](https://arktype.io/docs/blog/arkregex):
```ts
const Hex = type("/^[0-9a-fA-F]+$/")
// Type<string>
const Semver = type("/^(\\d+)\\.(\\d+)\\.(\\d+)$/")
// Type<`${number}.${number}.${number}`>
```
#### e(x)ec mode
Prefix a regex literal with `x` to parse capture groups at runtime, fully typed:
```ts
const User = type({
birthday: "x/^(?<month>\\d{2})-(?<day>\\d{2})-(?<year>\\d{4})$/"
})
const data = User.assert({ birthday: "05-21-1993" })
// fully type-safe
data.birthday.groups.month // "05"
data.birthday.groups.day // "21"
data.birthday.groups.year // "1993"
```
For the standalone package (no ArkType required), see the full [arkregex announcement](https://arktype.io/docs/blog/arkregex).
### lengths
Constrain a string with an inclusive or exclusive min or max length.
**string**
```ts
const Bounded = type({
nonEmpty: "string > 0",
atLeastLength3: "string.alphanumeric >= 3",
lessThanLength10: "string < 10",
atMostLength5: "string <= 5"
})
```
**fluent**
```ts
const Bounded = type({
nonEmpty: type.string.moreThanLength(0),
atLeastLength3: type.keywords.string.alphanumeric.atLeastLength(3),
lessThanLength10: type.string.lessThanLength(10),
atMostLength5: type.string.atMostLength(5)
})
```
Range expressions allow you to specify both a min and max length and use the same syntax for exclusivity.
**string**
```ts
const Range = type({
nonEmptyAtMostLength10: "0 < string <= 10",
integerStringWith2To5Digits: "2 <= string.integer < 6"
})
```
**fluent**
```ts
const Range = type({
nonEmptyAtMostLength10: