### Vitest Global Setup for Attest Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Create a global setup file for Vitest to initialize Attest. Configuration options can be passed to the setup function. ```typescript import { setup } from "@ark/attest" // config options can be passed here export default () => setup({}) ``` -------------------------------- ### Setup Attest with Options Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Configure attest's setup function with options like skipTypes and benchPercentThreshold. ```typescript import * as attest from "@ark/attest" export const setup = () => attest.setup({ skipTypes: true, benchPercentThreshold: 10 }) ``` -------------------------------- ### Install Attest Package Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Install the Attest package using npm. This package is currently in alpha. ```bash npm install @ark/attest ``` -------------------------------- ### Mocha Global Setup and Teardown for Attest Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Create a setup file for Mocha to initialize and teardown Attest. This file exports functions for global setup and teardown. ```typescript import { setup, teardown } from "@ark/attest" // config options can be passed here export const mochaGlobalSetup = () => setup({}) export const mochaGlobalTeardown = teardown ``` -------------------------------- ### Vitest Configuration for Attest Setup Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Configure Vitest to use a global setup file for Attest. This ensures Attest is initialized before tests run. ```typescript import { defineConfig } from "vitest/config" export default defineConfig({ test: { globalSetup: ["setupVitest.ts"] } }) ``` -------------------------------- ### Mocha Configuration for Attest Setup Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Configure Mocha in `package.json` to require a setup file for Attest. This ensures Attest is initialized before tests run. ```json "mocha": { "require": "./setupMocha.ts" } ``` -------------------------------- ### Setup Attest with Custom Aliases Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Integrates Attest into custom assertion libraries by calling `setup` with `attestAliases`. This ensures type data is collected from your custom assertion functions. Setup must occur before the first test runs. ```typescript // attest will only collect type data from functions with names listed in `attestAliases` setup({ attestAliases: ["yourCustomAssert"] }) // There are many other config options, but some are primarily internal- use others at your own risk! ``` -------------------------------- ### Run Development Server Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/README.md Commands to start the Next.js development server using npm, pnpm, or yarn. ```bash npm run dev # or pnpm dev # or yarn dev ``` -------------------------------- ### Primitive Constraints Examples Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Examples of primitive constraints that apply to data. These include rules for divisibility, pattern matching, numeric ranges, length, dates, and custom predicates. ```json { rule: 2 } ``` ```json { rule: "^[a-z]+$" } ``` ```json { rule: 0, exclusive: true } ``` ```json { rule: 100 } ``` ```json { rule: 1 } ``` ```json { rule: 255 } ``` ```json { rule: 10 } ``` ```json { rule: new Date("2000-01-01") } ``` ```json { rule: new Date() } ``` ```json { predicate: (n) => n % 2 === 1 } ``` -------------------------------- ### Scope Configuration Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx Configure validation rules for all types within a specific scope. This example sets a maximum age and customizes error messages for out-of-range values. ```typescript const myScope = scope( { User: { age: "number < 100" } }, { max: { actual: () => "unacceptably large" } } ) const types = myScope.export() // ArkErrors: age must be less than 100 (was unacceptably large) types.User({ name: "Alice", age: 101 }) const parsedAfter = myScope.type({ age: "number <= 100" }) // ArkErrors: age must be at most 100 (was unacceptably large) parsedAfter({ age: 101 }) ``` -------------------------------- ### Example Usage of Custom Assert API Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Demonstrates how a user would call a custom assertion function like `yourCustomAssert` with different type arguments and actual values. Includes examples of successful assertions and expected error cases. ```typescript import { yourCustomAssert } from "your-package" test("my code", () => { // Ok yourCustomAssert<"foo">(`${"f"}oo` as const) // Error: `Expected boolean, got true with relationship subtype` yourCustomAssert(true) // Error: `Expected 5, got number with relationship supertype` yourCustomAssert<5>(2 + 3) }) ``` -------------------------------- ### Define and Validate Environment Variables with ArkEnv Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/ecosystem/index.mdx Use ArkEnv to define a schema for your environment variables, validate them against the schema, and get a typesafe object. This example shows defining host, port, and node environment variables. ```typescript // @noErrors import arkenv from "arkenv" const env = arkenv({ HOST: "string.host", PORT: "number.port", NODE_ENV: "'development' | 'production' | 'test' = 'development'" }) // Automatically validate and parse process.env // TypeScript knows the ✨exact✨ types! console.log(env.HOST) // (property) HOST: string console.log(env.PORT) // (property) PORT: number console.log(env.NODE_ENV) // (property) NODE_ENV: "development" | "production" | "test" ``` -------------------------------- ### Benchmarking with Threshold Flags Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Example of running benchmarks with flags to error on threshold exceeded and set a specific percentage threshold. ```bash tsx ./p99/within-limit/p99-tall-simple.bench.ts --benchErrorOnThresholdExceeded --benchPercentThreshold 10 ``` -------------------------------- ### Example Usage of Thunk Definition Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/scopes/index.mdx Demonstrates the runtime usage of a scope defined with a thunk, showing input validation and transformation. ```typescript const types = $.export() // input is validated and transformed to: // [{ name: "Magical Crawdad", id: "777" }, { name: "Anonymous", id: "778" }] const groups = types.expandUserGroup([ { name: "Magical Crawdad", id: "777" }, "778" ]) ``` -------------------------------- ### Run Attest Stats Command Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Summarizes key type performance metrics for packages. Expects package directories as arguments, with `packages/*` as a glob pattern example. Defaults to CWD if no directories are provided. ```bash npm run attest stats packages/* ``` -------------------------------- ### Index Signature Constraint Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/internal/index.mdx Defines index signatures for objects, similar to `[key: string]: value`. ```json { key: "string", value: "boolean" } ``` -------------------------------- ### Sequence Constraint Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/internal/index.mdx Defines array patterns with tuples, rest elements, and variadic parts. ```json { sequence: { prefix: ["string", "number"] } } ``` -------------------------------- ### Skip Types Script Example Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Configure npm scripts to run tests with and without type checking using the ATTEST_skipTypes environment variable. ```json "test": "ATTEST_skipTypes=1 vitest run", "testWithTypes": "vitest run", ``` -------------------------------- ### Equivalent ArkType Type Definition Source: https://github.com/arktypeio/arktype/blob/main/ark/json-schema/README.md Demonstrates the ArkType equivalent of the JSON Schema converted in the previous example. ```javascript import { type } from "arktype" const T = type("5<=string<=10") ``` -------------------------------- ### Global Configuration Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx Configure ArkType globally by importing and calling `configure` from `arktype/config` in a separate file before importing ArkType. This is essential for options like `numberAllowsNaN` to affect built-in keywords. ```typescript import { configure } from "arktype/config" // use the "arktype/config" entrypoint configure({ numberAllowsNaN: true }) ``` ```typescript import "./config.ts" // import your config file before arktype import { type } from "arktype" type.number.allows(Number.NaN) // true ``` -------------------------------- ### Type-Specific Configuration Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx Configure a specific type to modify its validation behavior, such as customizing error messages. This example prevents logging the actual value for a password field. ```typescript // avoid logging "was xxx" for password const Password = type("string >= 8").configure({ actual: () => "" }) const User = type({ email: "string.email", password: Password }) // ArkErrors: password must be at least length 8 const out = User({ email: "david@arktype.io", password: "ez123" }) ``` -------------------------------- ### Targeted Configuration with `configure` Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.2.mdx Apply configuration to specific node kinds within a type using selectors. This example adds a 'description' to all 'domain' nodes in a User type, affecting both 'name' and 'age' properties. ```typescript const User = type({ name: "string", age: "number" }) // add the description to all domain nodes const configured = User.configure({ description: "a special string" }, "domain") configured.get("name").description // "a special string" configured.get("age").description // "a special string" ``` -------------------------------- ### Exact Optional Property Types Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx Demonstrates how ArkType handles optional properties by default, treating them as if `exactOptionalPropertyTypes` is true in TypeScript. Shows valid and invalid data when `key?` is defined. ```typescript const MyObj = type({ "key?": "number" }) // valid data const validResult = MyObj({}) // Error: key must be a number (was undefined) const errorResult = MyObj({ key: undefined }) ``` -------------------------------- ### Setup Attest with TypeScript Versions Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Configures Attest to test multiple TypeScript versions simultaneously using the `tsVersions` setting. Aliases must be npm dependencies or specified with the `npm:` prefix. '*' runs all discovered versions. ```typescript import { setup } from "@ark/attest" /** A string or list of strings representing the TypeScript version aliases to run. * * Aliases must be specified as a package.json dependency or devDependency beginning with "typescript". * Alternate aliases can be specified using the "npm:" prefix: * ```json * "typescript": "latest", * "typescript-next": "npm:typescript@next", * "typescript-1": "npm:typescript@5.2" * "typescript-2": "npm:typescript@5.1" * ``` * * "*" can be pased to run all discovered versions beginning with "typescript". */ setup({ tsVersions: "*" }) ``` -------------------------------- ### Structural Constraints Examples Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Examples of structural constraints that define the shape of objects and arrays. These include defining sequences for tuples, rest elements, variadic parts, and object properties. ```json { sequence: { prefix: ["string", "number"] } } ``` ```json { key: "id", value: "number" } ``` ```json { key: "name", value: "string" } ``` ```json { key: "string", value: "boolean" } ``` -------------------------------- ### Optional Property Constraint Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/internal/index.mdx Defines an optional property in an object structure. ```json { key: "name", value: "string" } ``` -------------------------------- ### Benchmarking API with Baseline Expression Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Benchmark API performance while excluding type instantiations from baseline expression setup. Includes type instantiation counts. ```typescript import { bench } from "@ark/attest" import { type } from "arktype" // baseline expression type("boolean") bench("single-quoted", () => { const _ = type("'nineteen characters'") // would be 2697 without baseline }).types([610, "instantiations"]) bench("keyword", () => { const _ = type("string") // would be 2507 without baseline }).types([356, "instantiations"]) ``` -------------------------------- ### External Generic Wrapper (Advanced) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/generics/index.mdx An advanced example of a generic wrapper function `createBox` that uses `type.raw` and type instantiation for deeper integration. It demonstrates creating a `BoxType` with a `string` definition. ```typescript const createBox = ( of: type.validate ): type.instantiate<{ of: def }> => type.raw({ box: of }) as never // Type<{ box: string }> const BoxType = createBox("string") ``` -------------------------------- ### Validated Function Definition and Usage Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.2.mdx Shows how to define a function with runtime-validated parameters and return types using `type.fn`. Includes an example of a `TraversalError` when validation fails. ```typescript // @errors: 2345 const len = type.fn("string | unknown[]", ":", "number")(s => s.length) len("foo") // 3 len([1, 2]) // 2 len.expression // "(string | Array) => number" len(true) // TraversalError: value at [0] must be a string or an object (was boolean) ``` -------------------------------- ### Pipe with Arguments Syntax Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Define a string type with a pipe that trims whitespace from the start using arguments syntax. ```typescript const trimStringStart = type("string", "=>", str => str.trimStart()) ``` -------------------------------- ### Configuring Errors by Code Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx Errors can be configured globally or by scope using their associated `code` property. This example shows how to customize the `expected` and `problem` messages for a 'divisor' error code. ```typescript const mod = type.module( { isEven: "number%2" }, { divisor: { // the available `ctx` types will include data specific to your errors expected: ctx => `% ${ctx.rule} !== 0`, problem: ctx => `${ctx.actual} ${ctx.expected}` } } ) // ArkErrors: 3 % 2 !== 0 mod.isEven(3) ``` -------------------------------- ### Integrating Runtime Logic with Type Assertions Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Demonstrates how to flexibly combine runtime logic with type assertions in Attest. This example conditionally asserts types based on the TypeScript version under test. ```typescript it("integrate runtime logic with type assertions", () => { const ArrayOf = type("", "t[]") const numericArray = arrayOf("number | bigint") // flexibly combine runtime logic with type assertions to customize your // tests beyond what is possible from pure static-analysis based type testing tools if (getTsVersionUnderTest().startsWith("5")) { // this assertion will only occur when testing TypeScript 5+! attest<(number | bigint)[]>(numericArray.infer) } }) ``` -------------------------------- ### JSON Schema Type Safety (Numeric) Source: https://github.com/arktypeio/arktype/blob/main/ark/json-schema/README.md Import `JsonSchema` from `arktype` to get type safety for your JSON Schema definitions. This example shows a numeric schema with an invalid `multipleOf` type. ```typescript import type { JsonSchema } from "arktype" const integerSchema: JsonSchema.Numeric = { type: "integer", multipleOf: "3" // errors stating that 'multipleOf' must be a number } ``` -------------------------------- ### Create a case-insensitive Regex type Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Use the `regex` function from `arkregex` to create a typed regular expression instance. This example demonstrates creating a case-insensitive regex that matches the exact string 'ok'. ```typescript import { regex } from "arkregex" const ok = regex("^ok$", "i") // Regex<"ok" | "oK" | "Ok" | "OK", { flags: "i" }> ``` -------------------------------- ### String Patterns: Exec Mode for Capture Groups Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/primitives/index.mdx Enables runtime parsing of regex capture groups for fully typed access to extracted data, demonstrated with a birthday example. ```typescript const User = type({ birthday: "x/^(?\d{2})-(?\d{2})-(?\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" ``` -------------------------------- ### N-ary 'pipe' Method for Chaining Transformations Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt The '.pipe(...morphsOrTypes)' method accepts multiple arguments to define a chain of transformations. This example trims whitespace and ensures a minimum length. ```typescript const trimStartToNonEmpty = type.pipe( type.string, s => s.trimStart(), type.string.atLeastLength(1) ) ``` -------------------------------- ### External Generic Wrapper (Basic) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/generics/index.mdx A basic example of creating a generic wrapper function `createBox` that takes a type `t` and returns a schema for an object with a `box` property of that type. It shows a type error when attempting to use an incorrect type. ```typescript const createBox = (of: type.Any) => type({ box: of }) // @ts-expect-error createBox(type("number")) // Type<{ box: string }> const BoxType = createBox(type("string")) ``` -------------------------------- ### TypeScript `keyof` Inconsistency Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/objects/index.mdx Demonstrates a potential pitfall in TypeScript where `keyof` can produce different results for types that appear identical, highlighting ArkType's intentional divergence to ensure type consistency. ```typescript type Thing1 = { [x: string]: unknown } // Thing2 is apparently identical to Thing1 type Thing2 = Record // and yet... type Key1 = keyof Thing1 // ^? type Key2 = keyof Thing2 // ^? ``` -------------------------------- ### Configure toJsonSchema Fallback Globally Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx Set a root-level `fallback` handler to simplify configuration when a single strategy applies to all incompatible types. This example uses a function that returns the base schema, effectively ignoring incompatible constraints. ```typescript const T = type({ "[symbol]": "string", birthday: "Date" }) //--- cut --- const schema = T.toJsonSchema({ // "just make it work" fallback: ctx => ctx.base }) ``` -------------------------------- ### Run Attest Trace Command Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Creates a trace.json file for type performance visualization and hot spot analysis. Expects a single argument for the root directory of the package. ```bash npm run attest trace . ``` -------------------------------- ### Filter Expression Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Use a filter expression to validate the input of a type before morphs are applied. This example limits the input string length. ```typescript const ShortNumeric = type("string.numeric.parse").filter((s, ctx) => { // s is a string here (the input), not a number (the output) if (s.length > 10) return ctx.reject("at most 10 characters") return true }) // the filter runs on the input (string) before the morph parses it ShortNumeric("123") // 123 ShortNumeric("12345678901") // ArkErrors: must be at most 10 characters ``` -------------------------------- ### Accessing Object Property Types with get Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/objects/index.mdx Use the `get` operator to extract the Type of a value based on a specified key from an object. Nested properties can be accessed by passing additional arguments. ```typescript const snorfUsage = type.enumerated("eating plants", "looking adorable") const Manatee = type({ isFriendly: "true", snorf: { uses: snorfUsage.array() } }) const True = Manatee.get("isFriendly") // nested properties can be accessed directly by passing additional args const SnorfUses = Manatee.get("snorf", "uses") ``` -------------------------------- ### Completion Snapshotting with Attest Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Demonstrates snapshotting expected completions for string literals, keys, or index access using Attest. Handles potential expression throwing by prepending `() =>`. ```typescript it("completion snapshotting", () => { // snapshot expected completions for any string literal! // @ts-expect-error (if your expression would throw, prepend () =>) attest(() => type({ a: "a", b: "b" })).completions({ a: ["any", "alpha", "alphanumeric"], b: ["bigint", "boolean"] }) type Legends = { faker?: "🐐"; [others: string]: unknown } // works for keys or index access as well (may need prettier-ignore to avoid removing quotes) // prettier-ignore attest({ "f": "🐐" } as Legends).completions({ "f": ["faker"] }) }) ``` -------------------------------- ### Function with Default and Variadic Parameters Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.2.mdx Illustrates defining functions with default parameter values and variadic array parameters using `type.fn` syntax. ```typescript // "string = 'world'" means the second param defaults to "world" if omitted const greet = type.fn( "string", "string = 'world'" )((greeting, name) => `${greeting}, ${name}!`) greet("Hello") // "Hello, world!" greet("Hey", "David") // "Hey, David!" // "..." spreads a variadic array parameter, just like in tuple definitions const join = type.fn( "...", "string[]", ":", "string" )((...parts) => parts.join(',')) join.expression // "(...string[]) => string" ``` -------------------------------- ### Required Property Constraint Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/internal/index.mdx Defines a required property in an object structure. ```json { key: "id", value: "number" } ``` -------------------------------- ### Configure Metadata with Description (Fluent) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Use `configure` to add metadata like descriptions to types. The description is used in error messages. ```typescript // this validator's error message will now start with "must be a special string" const SpecialString = type("string").configure({ description: "a special string" }) // sugar for adding description metadata const SpecialNumber = type("number").describe("a special number") ``` -------------------------------- ### Select Unit Literals Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/internal/index.mdx Filters a Type's references to get all references representing literal values. ```typescript const T = type({ name: "string > 5", flag: "0 | 1" }) .array() .atLeastLength(1) // get all references representing literal values const literals = T.select("unit") // [Type<0>, Type<1>] ``` -------------------------------- ### Define Function with Default and Optional Parameters Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Illustrates defining functions using `type.fn` that support default values for parameters and optional parameters. ```typescript const greet = type.fn( "string", "string = 'world'" )((greeting, name) => `${greeting}, ${name}!`) greet("Hello") // "Hello, world!" const maybeDouble = type.fn( "number", "boolean?" )((n, double) => (double ? n * 2 : n)) maybeDouble(5) // 5 maybeDouble(5, true) // 10 ``` -------------------------------- ### Unparalleled DX with Completions Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.0.mdx This snippet demonstrates ArkType's type syntax, emphasizing safety and advanced editor completions. It's useful for developers seeking a familiar syntax with enhanced tooling. ```typescript import { type } from "arktype" const parse = type({ name: "string", age: "number" }).parse console.log(parse({ name: "Alice", age: 30 })) // { name: "Alice", age: 30 } console.log(parse({ name: "Bob", age: "twenty" })) // Error: Expected number but received string in property "age" ``` -------------------------------- ### Pipe with Tuple Syntax Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Define a string type with a pipe that trims whitespace from the start using tuple syntax. ```typescript const trimStringStart = type(["string", "=>", str => str.trimStart()]) ``` -------------------------------- ### Define Function with Variadic Parameters Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Shows how to define a function type with `type.fn` that accepts a variable number of arguments using the `...` syntax. ```typescript const join = type.fn( "...", "string[]", ":", "string" )((...parts) => parts.join(',')) join.expression // "(...string[]) => string" ``` -------------------------------- ### Select Positive Number Literals Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/internal/index.mdx Filters a Type's references to get all references representing literal positive numbers. ```typescript const T = type({ name: "string > 5", flag: "0 | 1" }) .array() .atLeastLength(1) // get all references representing literal positive numbers const positiveNumberLiterals = T.select({ kind: "unit", where: u => typeof u.unit === "number" && u.unit > 0 }) // [Type<1>] ``` -------------------------------- ### Data Transformation with Pipe (Args) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Shows how to use `pipe` with the arguments API for sequential data transformations after validation. ```typescript // hover to see how morphs are represented at a type-level const trimStringStart = type("string", "=>", str => str.trimStart()) ``` -------------------------------- ### String Subtype Keywords for Date Formatting and Parsing Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/keywords.mdx Demonstrates using string subtypes for date formatting and parsing with string-based keywords. ```ts const Keywords = type({ dateFormattedString: "string.date", transformStringToDate: "string.date.parse", isoFormattedString: "string.date.iso", transformIsoFormattedStringToDate: "string.date.iso.parse" }) ``` -------------------------------- ### Pipe with Fluent Syntax Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Use the fluent .pipe() method to apply sequential morphs to a string type, trimming whitespace from the start. ```typescript const trimStringStart = type("string").pipe(str => str.trimStart()) ``` -------------------------------- ### Declare Object Type Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/declare.mdx Define an object type that matches an expected structure. This example shows how to declare a type with required and optional properties. ```typescript // @errors: 2322 type Expected = { a: string; b?: number } const T = type.declare().type({ a: "string", "b?": "number" }) ``` -------------------------------- ### Configure Metadata with Description (Arguments) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Configure metadata for types defined using the arguments syntax. The description is used in error messages. ```typescript // this validator's error message will now start with "must be a special string" const SpecialString = type("string", "@", { description: "a special string" }) // sugar for adding description metadata const SpecialNumber = type("number", "@", "a special number") ``` -------------------------------- ### Type to String Formatting Options Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Default prettier options for formatting type.toString output, optimized for type serialization. ```jsonc { "semi": false, // note this print width is optimized for type serialization, not general code "printWidth": 60, "trailingComma": "none", "parser": "typescript" } ``` -------------------------------- ### Type Casting with `as` (Fluent) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Use `as()` to specify how a type should be inferred without affecting runtime behavior. This example allows any string but suggests 'foo' and 'bar'. ```typescript // allow any string, but suggest "foo" and "bar" type AutocompletedString = "foo" | "bar" | (string & {}) const MyObj = type({ autocompletedString: type.string.as() }) ``` -------------------------------- ### Type and Value Assertions with Attest Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Demonstrates making assertions about types and values using Attest. Includes snapshotting for type information and JSON representations. ```typescript // @ark/attest assertions can be made from any unit test framework with a global setup/teardown describe("attest features", () => { it("type and value assertions", () => { const Even = type("number%2") // asserts even.infer is exactly number attest(even.infer) // make assertions about types and values seamlessly attest(even.infer).type.toString.snap("number") // including object literals- no more long inline strings! attest(even.json).snap({ intersection: [{ domain: "number" }, { divisor: 2 }] }) }) ``` -------------------------------- ### Arguments Syntax for Narrow Expressions Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Use arguments syntax with a narrow expression for custom validation. This example checks if two password fields are identical. ```typescript const Form = type( { password: "string", confirmPassword: "string" }, ":", (data, ctx) => { if (data.password === data.confirmPassword) { return true } return ctx.reject({ expected: "identical to password", // don't display the password in the error message! actual: "", path: ["confirmPassword"] }) } ) // ArkErrors: confirmPassword must be identical to password const out = Form({ password: "arktype", confirmPassword: "artkype" }) ``` -------------------------------- ### ArkType Matcher with Fluent API Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.1.mdx Demonstrates combining ArkType's Case Record and Fluent APIs to create a `sizeOf` matcher. It handles strings, numbers, and bigints directly, then uses a case for objects with a 'length' property, and defaults to 0 for all other inputs. ```typescript // the Case Record and Fluent APIs can be easily combined const sizeOf = match({ string: v => v.length, number: v => v, bigint: v => v }) // match any object with a numeric length property and extract it .case({ length: "number" }, o => o.length) // return 0 for all other data .default(() => 0) sizeOf("abc") // 3 sizeOf({ name: "David", length: 5 }) // 5 sizeOf(null) // 0 ``` -------------------------------- ### Inelegant Thunk Definition Example Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/scopes/index.mdx Illustrates an unconventional use of thunk definitions outside of scope definition, highlighting that while possible, it's generally not recommended. ```typescript // you *can* use them anywhere, but *should* you? (no) const MyInelegantType = type(() => type({ inelegantKey: () => type("'inelegant value'") }) ) ``` -------------------------------- ### Data Transformation with Pipe (Fluent) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Chain data transformations using `pipe` after validation. This example trims leading whitespace from a string using the fluent API. ```typescript // hover to see how morphs are represented at a type-level const trimStringStart = type("string").pipe(str => str.trimStart()) ``` -------------------------------- ### Recursive Type Definition with `this` Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Define recursive types using the `this` keyword to reference the root of the current definition. This example creates a nested structure for a gift box. ```typescript const DisappointingGift = type({ label: "string", "box?": "this" }) const out = DisappointingGift({ label: "foo", box: { label: "bar", box: {} } }) if (out instanceof type.errors) { // ArkErrors: box.box.label must be a string (was missing) console.error(out.summary) } else { // narrowed inference to arbitrary depth console.log(out.box?.box?.label) // ^? } ``` -------------------------------- ### Fluent Subtype Keywords for Date Formatting and Parsing Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/keywords.mdx Demonstrates using string subtypes for date formatting and parsing with the fluent API. ```ts const Keywords = type({ dateFormattedString: type.keywords.string.date.root, isoFormattedString: type.keywords.string.date.iso.root, transformStringToDate: type.keywords.string.date.parse, transformIsoFormattedStringToDate: type.keywords.string.date.iso.parse }) ``` -------------------------------- ### Matcher with Fluent API Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/match.mdx Demonstrates the fluent API of the `match` function, allowing chained method calls for defining cases and a default handler. This is useful for non-string-embeddable definitions. ```typescript import { match } from "arktype" // the Case Record and Fluent APIs can be easily combined const sizeOf = match({ string: v => v.length, number: v => v, bigint: v => v }) // match any object with a numeric length property and extract it .case({ length: "number" }, o => o.length) // return 0 for all other data .default(() => 0) sizeOf("abc") // 3 sizeOf({ name: "David", length: 5 }) // 5 sizeOf(null) // 0 ``` -------------------------------- ### Type Casting with `as` (Tuple) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Use `as type.cast` to specify how a type should be inferred without affecting runtime behavior. This example allows any string but suggests 'foo' and 'bar'. ```typescript // allow any string, but suggest "foo" and "bar" type AutocompletedString = "foo" | "bar" | (string & {}) const MyObj = type({ autocompletedString: "string" as type.cast }) ``` -------------------------------- ### Number Keywords: Epoch and Integer Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/primitives/index.mdx Illustrates using built-in number keywords for epoch timestamps and non-negative integers. ```typescript const User = type({ createdAt: "number.epoch", age: "number.integer >= 0" }) ``` -------------------------------- ### Define Tuple with Postfix Elements (String Syntax) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/objects/index.mdx Define a tuple with required elements following a variadic element using string syntax. ```typescript // allows zero or more numbers followed by a boolean, then a string const MyTuple = type(["...", "number[]", "boolean", "string"]) ``` -------------------------------- ### JSON Schema Type Safety (String) Source: https://github.com/arktypeio/arktype/blob/main/ark/json-schema/README.md For string schemas, import `StringSchema` from `@ark/json-schema` to ensure type safety. This example highlights an invalid `minLength` type. ```typescript import type { StringSchema } from "@ark/json-schema" const stringSchema: StringSchema = { type: "string", minLength: "3" // errors stating that 'minLength' must be a number } ``` -------------------------------- ### Select MinLength Constraints Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/internal/index.mdx Filters a Type's references to get all minLength constraints at the root of the Type. The shallow filter excludes constraints on nested properties. ```typescript const T = type({ name: "string > 5", flag: "0 | 1" }) .array() .atLeastLength(1) // get all minLength constraints at the root of the Type const minLengthConstraints = T.select({ kind: "minLength", // the shallow filter excludes the constraint on `name` boundary: "shallow" }) // [MinLengthNode<1>] ``` -------------------------------- ### Configure Metadata with Description (Tuple) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Configure metadata for types defined using the tuple syntax. The description is used in error messages. ```typescript // this validator's error message will now start with "must be a special string" const SpecialString = type([ "string", "@", { description: "a special string" } ]) // sugar for adding description metadata const SpecialNumber = type(["number", "@", "a special number"]) ``` -------------------------------- ### Tuple Syntax for Narrow Expressions Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Define a type with custom validation logic using tuple syntax and a narrow expression. This example ensures password confirmation matches. ```typescript const Form = type([ { password: "string", confirmPassword: "string" }, ":", (data, ctx) => { if (data.password === data.confirmPassword) { return true } return ctx.reject({ expected: "identical to password", // don't display the password in the error message! actual: "", path: ["confirmPassword"] }) } ]) // ArkErrors: confirmPassword must be identical to password const out = Form({ password: "arktype", confirmPassword: "artkype" }) ``` -------------------------------- ### Fluent Syntax for Narrow Expressions Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Use the fluent API with a narrow expression to add custom validation logic. This example checks if two password fields match. ```typescript const Form = type({ password: "string", confirmPassword: "string" }).narrow((data, ctx) => { if (data.password === data.confirmPassword) { return true } return ctx.reject({ expected: "identical to password", // don't display the password in the error message! actual: "", path: ["confirmPassword"] }) }) // ArkErrors: confirmPassword must be identical to password const out = Form({ password: "arktype", confirmPassword: "artkype" }) ``` -------------------------------- ### ArkType with exactOptionalPropertyTypes Disabled Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx Shows how to use ArkType after configuring `exactOptionalPropertyTypes` to `false`. Both an empty object and an object with `key: undefined` are now considered valid. ```typescript import "./config.ts" // import your config file before arktype import { type } from "arktype" const MyObj = type({ "key?": "number" }) // valid data const validResult = MyObj({}) // now also valid data (would be an error by default) const secondResult = MyObj({ key: undefined }) ``` -------------------------------- ### Configure TS Grammar for ArkType Highlighting Source: https://github.com/arktypeio/arktype/blob/main/ark/extension/README.md Temporarily replace the default TypeScript grammar in package.json to test standalone ArkType highlighting rules. Remember to revert this change before publishing. ```json "grammars": { "scopeName": "source.ts", "language": "typescript", "path": "tsWithArkType.tmLanguage.json" } ``` -------------------------------- ### Scoped Generics Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/generics/index.mdx Defines a generic type `box` within a scope, which is then instantiated as `bitBox` with specific types for `t` and `u`. The example shows invoking the `bitBox` type. ```typescript import { scope } from "arktype" const types = scope({ "box": { box: "t | u" }, bitBox: "box<0, 1>" }).export() const out = types.bitBox({ box: 0 }) ``` -------------------------------- ### Union Type Warnings and Errors Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Understand when unions can lead to `ParseError` due to overlapping operands that also transform data. This example shows valid and invalid union configurations. ```typescript // operands overlap, but neither transforms data const Okay = type("number > 0").or("number < 10") // operand transforms data, but there's no overlap between the inputs const AlsoOkay = type("string.numeric.parse").or({ box: "string" }) // operands overlap and transform data, but in the same way const StillOkay = type("string > 5", "=>", Number.parseFloat).or([ "0 < string < 10", "=>", Number.parseFloat ]) // ParseError: An unordered union of a type including a morph and a type with overlapping input is indeterminate const Bad = type({ box: "string.numeric.parse" }).or({ box: "string" }) const SameError = type({ a: "string.numeric.parse" }).or({ b: "string.numeric.parse" }) ``` -------------------------------- ### String Syntax for Brands Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Define a branded type using string-based syntax. Brands add compile-time only constraints. ```typescript // @noErrors const Even = type("(number % 2)#even") type Even = typeof Even.infer const good: Even = Even.assert(2) // TypeScript: Type 'number' is not assignable to type 'Brand' const bad: Even = 5 ``` -------------------------------- ### Integrated Type Performance Benchmarking Source: https://github.com/arktypeio/arktype/blob/main/ark/attest/README.md Shows how to use Attest for integrated type performance benchmarking. It reports the number of type instantiations within a `bench` call. ```typescript it("integrated type performance benchmarking", () => { const User = type({ kind: "'admin'", "powers?": "string[]" }) .or({ kind: "'superadmin'", "superpowers?": "string[]" }) .or({ kind: "'pleb'" }) attest.instantiations([7574, "instantiations"]) }) }) ``` -------------------------------- ### N-ary Pipe Operator Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.2.mdx Create a pipeline of transformations using the standalone `type.pipe` function, which accepts variadic arguments. This example pipes a string through trimming and then ensures it's non-empty. ```typescript const TrimToNonEmpty = type.pipe( type.string, s => s.trimStart(), type.string.atLeastLength(1) ) ``` -------------------------------- ### Morph-Aware `type.declare` with Side Context Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.2.mdx Declare types with awareness of morphs (transformations) by specifying the 'side' context. This example declares only the input shape for a type that includes a 'string.numeric.parse' morph. ```typescript type Input = { name: string } // { side: "in" } means we're declaring only the input shape const T = type.declare ().type({ name: "string.numeric.parse" }) ``` -------------------------------- ### High-Kind Type (HKT) Implementation of Partial Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/generics/index.mdx Illustrates the internal implementation of a `Partial` generic using ArkType's High-Kind Type (HKT) system, allowing arbitrary external types to be integrated as native generics. ```typescript import { generic, Hkt } from "arktype" const Partial = generic(["T", "object"]) (args => args.T.partial(), class PartialHkt extends Hkt<[object]> { declare body: Partial }) ``` -------------------------------- ### Using `type.module` Sugar for Inline Scope Export Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/scopes/index.mdx Shows the equivalent of the inline export pattern using the `type.module` shorthand. ```typescript const ezModule = type.module({ Ez: "'moochi'" }) ``` -------------------------------- ### Filtering Schema References with `select` Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/introspection/index.mdx Use `select` to filter a Type's references based on their internal representation. This example shows how to extract literal values and constraints from a schema. ```typescript const T = type({ name: "string > 5", flag: "0 | 1" }) .array() .atLeastLength(1) // get all references representing literal values const literals = T.select("unit") // [Type<0>, Type<1>] // get all references representing literal positive numbers const positiveNumberLiterals = T.select({ kind: "unit", where: u => typeof u.unit === "number" && u.unit > 0 }) // [Type<1>] // get all minLength constraints at the root of the Type const minLengthConstraints = T.select({ kind: "minLength", // the shallow filter excludes the constraint on `name` boundary: "shallow" }) // [MinLengthNode<1>] ``` -------------------------------- ### Selective Metadata Configuration (Arguments) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/expressions/index.mdx Configure metadata selectively on parts of a type using a `NodeSelector` in arguments syntax. The description is applied to all domain keywords. ```typescript const SelectivelyConfigured = type( { name: "string", age: "number" }, "@", { description: "a special string" }, // add the description to all domain keywords "domain" ) SelectivelyConfigured.get("name").description // "a special string" SelectivelyConfigured.get("age").description // "a special string" ``` -------------------------------- ### Accessing and Serializing ArkErrors Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/configuration/index.mdx The `ArkErrors` array contains `ArkError` instances that can be discriminated by code (e.g., `.hasCode('divisor')`) and serialized to JSON. This example demonstrates accessing structured error data. ```typescript const T = type({ n: "number % 2 >= 2" }) const out = T({ n: 1 }) if (out instanceof type.errors) { out.flatByPath // { n: [{ data: 1, path: ["n"], code: "divisor", ... }, { data: 1, path: ["n"], code: "min", ... }] } out.flatProblemsByPath // { n: ["must be even (was 1)", "must be at least 2 (was 1)"] } } ``` -------------------------------- ### Data Transformation with Pipe (Tuple) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Demonstrates data transformation with `pipe` using the tuple API, allowing sequential morphs after validation. ```typescript // hover to see how morphs are represented at a type-level const trimStringStart = type(["string", "=>", str => str.trimStart()]) ``` -------------------------------- ### ArkType Type and Variable Casing Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/faq.mdx Demonstrates the distinction between PascalCase for entities/non-generic types and camelCase for generic types with verb names or parameter names in ArkType. ```typescript const User = type({ name: "string", platform: "'android' | 'ios'", "version?": "number | string" }) const parseJson = type("string.json.parse").to({ name: "string", version: "string.semver" }) ``` -------------------------------- ### Optional Property Declaration in `type.declare` Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/blog/2.2.mdx Express optionality for properties directly within the type definition when using `type.declare`. This example declares a type with an optional 'b' property of type number. ```typescript type Expected = { a: string; b?: number } const T = type.declare().type({ a: "string", // previously failed with "b?" is missing" b: "number?" }) ``` -------------------------------- ### Define Tuple with Postfix Elements (Fluent Syntax) Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/content/docs/objects/index.mdx Define a tuple with required elements following a variadic element using the fluent API. ```typescript // allows zero or more numbers followed by a boolean, then a string const MyTuple = type(["...", type.number.array(), type.boolean, type.string]) ``` -------------------------------- ### Configure Root Fallback Handler for toJsonSchema Source: https://github.com/arktypeio/arktype/blob/main/ark/docs/public/llms.txt Set a simple root fallback handler for toJsonSchema() to 'just make it work' by returning the base schema, effectively ignoring incompatible constraints. ```typescript const T = type({ "[symbol]": "string", birthday: "Date" }) const schema = T.toJsonSchema({ // "just make it work" fallback: ctx => ctx.base }) ```