ArkType

TypeScript's 1:1 validator, optimized from editor to runtime

README

ArkType


TypeScript's 1:1 validator

What is it?


ArkType is a runtime validation library that can infer TypeScript definitions 1:1 and reuse them as highly-optimized validators for your data.

With each character you type, you'll get immediate feedback from your editor in the form of either a fully-inferred Type or a specific and helpful ParseError.

This result exactly mirrors what you can expect to happen at runtime down to the punctuation of the error message- no plugins required.


  1. ```ts @blockFrom:dev/test/examples/type.ts
  2. import { type } from "arktype"

  3. // Definitions are statically parsed and inferred as TS.
  4. export const user = type({
  5.     name: "string",
  6.     device: {
  7.         platform: "'android'|'ios'",
  8.         "version?": "number"
  9.     }
  10. })

  11. // Validators return typed data or clear, customizable errors.
  12. export const { data, problems } = user({
  13.     name: "Alan Turing",
  14.     device: {
  15.         // problems.summary: "device/platform must be 'android' or 'ios' (was 'enigma')"
  16.         platform: "enigma"
  17.     }
  18. })
  19. ```

Check out how it works, try it in-browser, or scroll slightly to read about installation.



## Install 📦`12KB` gzipped, `0` dependencies

Npm Icon npm install arktype(or whatever package manager you prefer)

Our types are tested in strict-mode with TypeScript versions4.8, 4.9, and 5.0.

_Our APIs have mostly stabilized, but details may still change during the alpha/beta stages of our 1.0 release. If you have suggestions that may require a breaking change, now is the time to let us know!_ ⛵


Scopes



  1. ```ts @blockFrom:dev/test/examples/scope.ts
  2. import { scope } from "arktype"

  3. // Scopes are collections of types that can reference each other.
  4. export const types = scope({
  5.     package: {
  6.         name: "string",
  7.         "dependencies?": "package[]",
  8.         "contributors?": "contributor[]"
  9.     },
  10.     contributor: {
  11.         // Subtypes like 'email' are inferred like 'string' but provide additional validation at runtime.
  12.         email: "email",
  13.         "packages?": "package[]"
  14.     }
  15. }).compile()

  16. // Cyclic types are inferred to arbitrary depth...
  17. export type Package = typeof types.package.infer

  18. // And can validate cyclic data.
  19. const packageData: Package = {
  20.     name: "arktype",
  21.     dependencies: [{ name: "typescript" }],
  22.     contributors: [{ email: "david@sharktypeio" }]
  23. }
  24. packageData.dependencies![0].dependencies = [packageData]

  25. export const { data, problems } = types.package(packageData)
  26. ```

Syntax


This is an informal, non-exhaustive list of current and upcoming ArkType syntax.

There are some subjects it doesn't cover, primarily tuple expressions and scopes. As mentioned below, keep an eye out for comprehensive docs coming with the upcoming beta release. In the meantime, join our Discord or head to our GitHub Discussions to ask a question and there's a good chance you'll see a response within the hour 😊

  1. ```ts
  2. export const currentTsSyntax = type({
  3.     keyword: "null",
  4.     stringLiteral: "'TS'",
  5.     numberLiteral: "5",
  6.     bigintLiteral: "5n",
  7.     union: "string|number",
  8.     intersection: "boolean&true",
  9.     array: "Date[]",
  10.     grouping: "(0|1)[]",
  11.     objectLiteral: {
  12.         nested: "string",
  13.         "optional?": "number"
  14.     },
  15.     tuple: ["number", "number"]
  16. })

  17. // these features will be available in the upcoming release

  18. export const upcomingTsSyntax = type({
  19.     keyof: "keyof bigint",
  20.     thisKeyword: "this", // recurses to the root of the current type
  21.     variadicTuples: ["true", "...false[]"]
  22. })

  23. export const validationSyntax = type({
  24.     keywords: "email|uuid|creditCard|integer", // and many more
  25.     builtinParsers: "parsedDate", // parses a Date from a string
  26.     nativeRegexLiteral: /@arktype\.io/,
  27.     embeddedRegexLiteral: "email&/@arktype\\.io/",
  28.     divisibility: "number%10", // a multiple of 10
  29.     bound: "alpha>10", // an alpha-only string with more than 10 characters
  30.     range: "1<=email[]<99", // a list of 1 to 99 emails
  31.     narrows: ["number", "=>", (n) => n % 2 === 1], // an odd integer
  32.     morphs: ["string", "|>", parseFloat] // validates a string input then parses it to a number
  33. })

  34. // in the upcoming release, you can use chaining to define expressions directly
  35. // that use objects or functions that can't be embedded in strings

  36. export const parseBigintLiteral = type({ value: "string" })
  37.     .and({
  38.         format: "'bigint'"
  39.     })
  40.     .narrow((data): data is { value: `${string}n`; format: "bigint" } =>
  41.         data.value.endsWith("n")
  42.     )
  43.     .morph((data) => BigInt(data.value.slice(-1)))

  44. export const { data, problems } = parseBigintLiteral("999n")
  45. //             ^ bigint | undefined
  46. ```

API



ArkType supports many of TypeScript's built-in types and operators, as well as some new ones dedicated exclusively to runtime validation. In fact, we got a little ahead of ourselves and built a ton of cool features, but we're still working on getting caught up syntax and API docs. Keep an eye out for more in the next couple weeks ⛵

In the meantime, check out the examples here and use the type hints you get to learn how you can customize your types and scopes. If you want to explore some of the more advanced features, take a look at our unit tests or ask us on Discord if your functionality is supported. If not, create a GitHub issue so we can prioritize it!


Integrations


tRPC


ArkType can easily be used with tRPC via the assert prop:

  1. ```ts
  2. ...
  3. t.procedure
  4.   .input(
  5.     type({
  6.       name: "string",
  7.       "age?": "number"
  8.     }).assert
  9.   )
  10. ...
  11. ```

How?


ArkType's isomorphic parser has parallel static and dynamic implementations. This means as soon as you type a definition in your editor, you'll know the eventual result at runtime.

If you're curious, below is an example of what that looks like under the hood. If not, close that hood back up, npm install arktype and enjoy top-notch developer experience 🧑‍💻

  1. ```ts @blockFrom:src/parse/string/shift/operator/operator.ts:parseOperator
  2. export const parseOperator = (s: DynamicState): void => {
  3.     const lookahead = s.scanner.shift()
  4.     return lookahead === ""
  5.         ? s.finalize()
  6.         : lookahead === "["
  7.         ? s.scanner.shift() === "]"
  8.             ? s.rootToArray()
  9.             : s.error(incompleteArrayTokenMessage)
  10.         : isKeyOf(lookahead, Scanner.branchTokens)
  11.         ? s.pushRootToBranch(lookahead)
  12.         : lookahead === ")"
  13.         ? s.finalizeGroup()
  14.         : isKeyOf(lookahead, Scanner.comparatorStartChars)
  15.         ? parseBound(s, lookahead)
  16.         : lookahead === "%"
  17.         ? parseDivisor(s)
  18.         : lookahead === " "
  19.         ? parseOperator(s)
  20.         : throwInternalError(writeUnexpectedCharacterMessage(lookahead))
  21. }

  22. export type parseOperator<s extends StaticState> =
  23.     s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned>
  24.         ? lookahead extends "["
  25.             ? unscanned extends Scanner.shift<"]", infer nextUnscanned>
  26.                 ? state.setRoot<s, [s["root"], "[]"], nextUnscanned>
  27.                 : error<incompleteArrayTokenMessage>
  28.             : lookahead extends Scanner.BranchToken
  29.             ? state.reduceBranch<s, lookahead, unscanned>
  30.             : lookahead extends ")"
  31.             ? state.finalizeGroup<s, unscanned>
  32.             : lookahead extends Scanner.ComparatorStartChar
  33.             ? parseBound<s, lookahead, unscanned>
  34.             : lookahead extends "%"
  35.             ? parseDivisor<s, unscanned>
  36.             : lookahead extends " "
  37.             ? parseOperator<state.scanTo<s, unscanned>>
  38.             : error<writeUnexpectedCharacterMessage<lookahead>>
  39.         : state.finalize<s>
  40. ```

Contributions


We accept and encourage pull requests from outside ArkType.

Depending on your level of familiarity with type systems and TS generics, some parts of the codebase may be hard to jump into. That said, there's plenty of opportunities for more straightforward contributions.

If you're planning on submitting a non-trivial fix or a new feature, please create an issue first so everyone's on the same page. The last thing we want is for you to spend time on a submission we're unable to merge.

When you're ready, check out our guide to get started!

License


This project is licensed under the terms of the

Collaboration


I'd love to hear about what you're working on and how ArkType can help. Please reach out to david@arktype.io.

Code of Conduct


We will not tolerate any form of disrespect toward members of our community. Please refer to our Code of Conduct and reach out to david@arktype.io immediately if you've seen or experienced an interaction that may violate these standards.

Sponsorship


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

If the project has been useful to you and you are in a financial position to do so, please chip in via GitHub Sponsors.

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

Current Sponsors 🥰


[tmm](https://github.com/tmm)[xrexy](https://github.com/xrexy)[thomasballinger](https://github.com/thomasballinger)[codeandcats](https://github.com/codeandcats)|
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------|
|