ArkType

The ctx argument that narrow and pipe functions receive for reading the current path and reporting errors.

Functions you pass to .narrow and .pipe receive a ctx as their second argument. Use it to report errors that read like ArkType's own:

const const PowerOfTwo: Type<number>PowerOfTwo = type("number").narrow(
	(n, ctx) => Number.isInteger(Math.log2(n)) || ctx.mustBe("a power of 2")
)

// ArkErrors: must be a power of 2
PowerOfTwo(6)

A narrow returns ctx.mustBe(...) or ctx.reject(...), which add an error and return false. A morph returns ctx.error(...), which adds an error and returns it:

const const prices: Map<string, number>prices = new Map([
	["apple", 1.25],
	["pear", 0.75]
])

const const priceOf: Type<(In: string) => Out<number>>priceOf = type("string").pipe(
	(name, ctx) => const prices: Map<string, number>prices.get(name) ?? ctx.error("a product we sell")
)

// ArkErrors: must be a product we sell
priceOf("kiwi")

reject takes the parts of an error: expected and actual, or a message that replaces the whole sentence. It doesn't take a string, which would read as a sentence but say what the value must be: pass that to mustBe. error takes either, its string being what the value must be. relativePath reports it below the value being checked, where path would replace its whole path from the root of the data:

const 
const Range: Type<{
    start: number;
    end: number;
}>
Range
= type({ start: "number", end: "number" }).narrow(
(range, ctx) => range.start <= range.end || ctx.reject({ expected: "at least start", actual: `${range.end}`, relativePath: ["end"] }) ) // ArkErrors: end must be at least start (was 1) Range({ start: 2, end: 1 }) const
const Booking: Type<{
    stay: {
        start: number;
        end: number;
    };
}>
Booking
= type({ stay:
const Range: Type<{
    start: number;
    end: number;
}>
Range
}).narrow(
(booking, ctx) => booking.stay.end - booking.stay.start <= 30 || ctx.reject({ message: "Book 30 nights or fewer", relativePath: ["stay"] }) ) // ArkErrors: stay: Book 30 nights or fewer Booking({ stay: { start: 1, end: 60 } })

To write a check outside the call, type ctx with Traversal:

import { type, type Traversal } from "arktype"

const isPowerOfTwo = (n: number, ctx: Traversal) =>
	Number.isInteger(Math.log2(n)) || ctx.mustBe("a power of 2")

const const PowerOfTwo: Type<number>PowerOfTwo = type("number").narrow(isPowerOfTwo)

Context

A check that depends on something the caller has, like a form's saved values, reads it as ctx.context. Bind it with .withContext, so the Type stays defined once and can be precompiled, instead of being created again for each value it closes over. Declare its shape on ArkEnv:

import { type } from "arktype"

declare module "arktype" {
	interface ArkEnv {
		context(): { savedStreet?: string }
	}
}

// a street saved under older rules stays valid until it's edited
const const Street: Type<string>Street = type("string").narrow(
	(s, ctx) =>
		s === ctx.context?.savedStreet ||
		s.length > 3 ||
		ctx.mustBe("a full street")
)

const 
const Address: Type<{
    street: string;
    city: string;
}>
Address
= type({ street: const Street: Type<string>Street, city: "string" })
// ArkErrors: street must be a full street Address({ street: "Elm", city: "Springfield" }) // { street: "Elm", city: "Springfield" }
const Address: Type<{
    street: string;
    city: string;
}>
Address
.withContext({ savedStreet: "Elm" })({
street: "Elm", city: "Springfield" })

.withContext creates no Type. It returns a validator with assert, allows and ~standard, which is a Standard Schema a form library can take as is. Every narrow and morph the call reaches reads the same context, at any depth, and it's undefined in a call without one. A Standard Schema caller can also pass it without binding, as T["~standard"].validate(data, { libraryOptions: { context } }).

Members

.path

traversal

the path being validated or morphed

  • array indices represented as numbers
  • warning mutated during traversal - use path.slice(0) to snapshot
  • use propString for a stringified version

.root

traversal

the original value being traversed

.config

traversal

configuration for this traversal

  • options can affect traversal results and error messages
  • defaults < global config < scope config
  • does not include options configured on individual types

.context

traversal

the context this validation was called with

  • the same object at every path, for predicates and morphs to read
  • undefined when a call passes none
  • typed as declared on ArkEnv: interface ArkEnv { context(): {...} }

.hasError()

traversal

whether currentBranch (or the traversal root, outside a union) has one or more errors

.errors

traversal

ArkErrors that will be part of this traversal's finalized result

  • will always be empty for a valid traversal

.data

traversal

the data being validated or morphed

  • the value at path, as transformed by any morphs that have already run

.propString

traversal

a string representing path

example
const path = ["key1", Symbol("key2"), "key3", 4, "~key5"]
const const propString: "key1[Symbol(key2)].key3[4][\"~key5\"]"propString = 'key1[Symbol(key2)].key3[4]["~key5"]'

add an ArkError and return false

  • useful for predicates like .narrow
  • { message: "Enter a valid email" } is the whole sentence an issue says
  • to say what the value must be, as must be even, pass "even" to mustBe

add an ArkError from a description and return false

  • useful for predicates like .narrow
  • equivalent to reject({ expected })

.error(input)

traversal

add and return an ArkError

  • useful for morphs like .pipe
  • warning a string is what the value must be: error("valid JSON") reads must be valid JSON, so pass a sentence as { message }

.path

traversal

the path being validated or morphed

  • array indices represented as numbers
  • warning mutated during traversal - use path.slice(0) to snapshot
  • use propString for a stringified version

.root

traversal

the original value being traversed

.config

traversal

configuration for this traversal

  • options can affect traversal results and error messages
  • defaults < global config < scope config
  • does not include options configured on individual types

.context

traversal

the context this validation was called with

  • the same object at every path, for predicates and morphs to read
  • undefined when a call passes none
  • typed as declared on ArkEnv: interface ArkEnv { context(): {...} }

.hasError()

traversal

whether currentBranch (or the traversal root, outside a union) has one or more errors

.errors

traversal

ArkErrors that will be part of this traversal's finalized result

  • will always be empty for a valid traversal

.data

traversal

the data being validated or morphed

  • the value at path, as transformed by any morphs that have already run

.propString

traversal

a string representing path

example
const path = ["key1", Symbol("key2"), "key3", 4, "~key5"]
const const propString: "key1[Symbol(key2)].key3[4][\"~key5\"]"propString = 'key1[Symbol(key2)].key3[4]["~key5"]'

add an ArkError and return false

  • useful for predicates like .narrow
  • { message: "Enter a valid email" } is the whole sentence an issue says
  • to say what the value must be, as must be even, pass "even" to mustBe

add an ArkError from a description and return false

  • useful for predicates like .narrow
  • equivalent to reject({ expected })

.error(input)

traversal

add and return an ArkError

  • useful for morphs like .pipe
  • warning a string is what the value must be: error("valid JSON") reads must be valid JSON, so pass a sentence as { message }