Core functionality for creating and validating types using TypeScript-like syntax with runtime enforcement.
Creates a Type from a definition using familiar TypeScript syntax.
/**
* Create a Type from your definition
* @param def - Type definition (object, string, function, etc.)
* @returns Type instance for validation and inference
*/
function type<const def>(def: type.validate<def>): Type<type.infer<def>>;Usage Examples:
import { type } from "arktype";
// Primitive types
const StringType = type("string");
const NumberType = type("number");
// Object types
const User = type({
name: "string",
age: "number",
email: "string.email"
});
// Array types
const StringArray = type("string[]");
const UserArray = type([User]);
// Union types
const StringOrNumber = type("string | number");
// Complex nested types
const ApiResponse = type({
data: {
users: [{
id: "string",
profile: {
name: "string",
age: "number > 0"
}
}]
},
status: "'success' | 'error'",
timestamp: "string.date.iso"
});Creates parameterized types with constraints.
/**
* Create a Generic from a parameter string and body definition
* @param params - Parameter string like "<t, n extends number>"
* @param def - Definition using the parameter names
* @returns Generic type constructor
*/
function type<
const params extends ParameterString,
const def
>(
params: validateParameterString<params>,
def: type.validate<def, {}, baseGenericConstraints<parseValidGenericParams<params>>>
): Generic<parseValidGenericParams<params>, def>;Usage Examples:
// Basic generic
const Container = type("<t>", {
value: "t",
count: "number"
});
const StringContainer = Container("string");
const NumberContainer = Container("number");
// Generic with constraints
const NumericContainer = type("<t extends number>", {
value: "t",
doubled: "t"
});
const IntContainer = NumericContainer("number.integer");
// Multiple parameters
const KeyValue = type("<k extends string, v>", {
key: "k",
value: "v"
});
const StringNumberKV = KeyValue("string", "number");Creates types from tuple expressions spread as function arguments.
/**
* Create a Type from a tuple expression spread as arguments
* @param expressions - Tuple expression components
* @returns Type instance
*/
function type<const zero, const one, const rest extends array>(
_0: zero extends IndexZeroOperator ? zero : type.validate<zero>,
_1: one,
..._2: rest
): Type<type.infer<[zero, one, ...rest]>>;Usage Examples:
// Pipe transformation using tuple syntax
const ParseNumber = type("string", "=>", (s: string) => Number(s));
// Union with transformation
const StringOrParsedNumber = type("string", "|", ["number", "=>", (n: number) => n.toString()]);
// Range constraints (prefer string syntax)
const PositiveNumber = type("number > 0");
// Multiple operations
const ComplexType = type("string", "=>", (s: string) => s.trim(), "=>", (s: string) => s.length);
// Conditional logic
const ConditionalType = type("string | number", "=>", (input: string | number) =>
typeof input === "string" ? input.length : input * 2
);The Type class provides comprehensive validation and introspection capabilities.
interface Type<t = unknown> {
/** Validate data, return data or ArkErrors */
(data: unknown): t | ArkErrors;
/** Validate and return data or throw TraversalError */
assert(data: unknown): t;
/** Type guard that returns boolean */
allows(data: unknown): data is t;
/** Typed assertion for known input types */
from(literal: this["inferIn"]): this["infer"];
/** Get input-only type (no transformations) */
get in(): Type<this["inferIn"]>;
/** Get output-only type (transformed result) */
get out(): Type<this["inferIntrospectableOut"]>;
/** Configure type with metadata */
configure(meta: TypeMeta.MappableInput): this;
/** Add description to type */
describe(description: string): this;
/** Set undeclared key behavior for objects */
onUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
onDeepUndeclaredKey(behavior: UndeclaredKeyBehavior): this;
}Additional methods for creating specific types.
// Unit types (exact value matching)
function unit<const t>(value: t): Type<t>;
// Enumerated types (union of exact values)
function enumerated<const values extends readonly unknown[]>(
...values: values
): Type<values[number]>;
// TypeScript enum value types
function valueOf<const o extends object>(o: o): Type<o[keyof o]>;
// Class instance types
function instanceOf<const t extends object>(
ctor: Constructor<t>
): Type<t>;
// Raw type creation (no validation)
function raw(def: unknown): Type<any>;Usage Examples:
// Unit types
const Foo = type.unit("foo"); // Type<"foo">
const FortyTwo = type.unit(42); // Type<42>
// Enumerated types
const Color = type.enumerated("red", "green", "blue");
const Priority = type.enumerated(1, 2, 3, "urgent");
// Enum types
enum Status { Active, Inactive, Pending }
const StatusType = type.valueOf(Status); // Type<Status>
// Instance types
const DateType = type.instanceOf(Date);
const ErrorType = type.instanceOf(Error);TypeScript integration provides full type inference and validation.
// Type inference utilities
namespace type {
type infer<def> = inferDefinition<def>;
type validate<def> = validateDefinition<def>;
type instantiate<def> = instantiateType<inferDefinition<def>>;
}
// Distillation types
type distill.In<t> = /* input type extraction */;
type distill.Out<t> = /* output type extraction */;
type distill.introspectable.Out<t> = /* runtime-knowable output */;Usage Examples:
const User = type({
name: "string",
age: "number",
email: "string.email"
});
// TypeScript inference
type UserType = typeof User.infer;
// { name: string; age: number; email: string }
type UserInput = typeof User.inferIn;
// { name: string; age: number; email: string }
// With transformations
const ProcessUser = type({
name: "string.trim",
age: "string.integer.parse",
email: "string.email"
});
type ProcessedInput = typeof ProcessUser.inferIn;
// { name: string; age: string; email: string }
type ProcessedOutput = typeof ProcessUser.inferOut;
// { name: string; age: number; email: string }Additional parsing and validation utilities.
/**
* Pattern matching utility for conditional type construction
*/
function match<input>(input: input): MatchParser<input>;
/**
* Declare types with explicit type annotations
*/
function declare<T>(): { type: <const def>(def: def) => Type<T> };
/**
* Define type definitions without creating Type instances
*/
function define<const def>(def: def): def;Usage Examples:
// Pattern matching (advanced use case)
const processValue = match("string | number")
.when("string", s => s.toUpperCase())
.when("number", n => n * 2)
.finalize();
// Explicit type declaration
const UserId = declare<string>().type("string.uuid");
// Definition utility
const userDef = define({
name: "string",
age: "number.integer >= 0"
});
const User = type(userDef);