Json Schema Type Builder with Static Type Resolution for TypeScript
—
Runtime functions for validation, transformation, and manipulation of values against TypeBox schemas. The Value namespace provides comprehensive tools for working with data at runtime.
Returns boolean indicating if value matches schema.
/**
* Returns boolean if value matches schema
* @param schema - Schema to validate against
* @param value - Value to validate
* @returns True if value matches schema
*/
function Check<T extends TSchema>(schema: T, value: unknown, references?: TSchema[]): value is Static<T>;Usage Examples:
import { Type, Value } from "@sinclair/typebox";
const User = Type.Object({
name: Type.String(),
age: Type.Number()
});
const data1 = { name: "Alice", age: 25 };
const data2 = { name: "Bob", age: "30" };
console.log(Value.Check(User, data1)); // true
console.log(Value.Check(User, data2)); // false (age is string, not number)Asserts value matches schema, throws on failure.
/**
* Asserts value matches schema, throws on failure
* @param schema - Schema to validate against
* @param value - Value to validate
* @throws ValueError if validation fails
*/
function Assert<T extends TSchema>(schema: T, value: unknown, references?: TSchema[]): asserts value is Static<T>;Usage Examples:
try {
Value.Assert(User, { name: "Alice", age: 25 });
// Value is now typed as { name: string, age: number }
} catch (error) {
console.error("Validation failed:", error.message);
}Creates default values from schemas.
/**
* Creates default values from schemas
* @param schema - Schema to create value from
* @returns Default value matching schema structure
*/
function Create<T extends TSchema>(schema: T, references?: TSchema[]): Static<T>;Usage Examples:
const User = Type.Object({
name: Type.String({ default: "Anonymous" }),
age: Type.Number({ default: 0 }),
isActive: Type.Boolean({ default: true }),
tags: Type.Array(Type.String(), { default: [] })
});
const defaultUser = Value.Create(User);
// Result: { name: "Anonymous", age: 0, isActive: true, tags: [] }
// For types without defaults
const SimpleUser = Type.Object({
name: Type.String(),
age: Type.Number()
});
const simpleDefault = Value.Create(SimpleUser);
// Result: { name: "", age: 0 }Applies default values from schema to existing data.
/**
* Applies default values from schema
* @param schema - Schema containing default values
* @param value - Value to apply defaults to
* @returns Value with defaults applied
*/
function Default<T extends TSchema>(schema: T, value: unknown): Static<T>;Usage Examples:
const partialUser = { name: "Alice" };
const completeUser = Value.Default(User, partialUser);
// Result: { name: "Alice", age: 0, isActive: true, tags: [] }Casts value to match schema structure, converting compatible types.
/**
* Casts value to match schema structure
* @param schema - Target schema
* @param value - Value to cast
* @returns Value cast to match schema
*/
function Cast<T extends TSchema>(schema: T, value: unknown): Static<T>;Usage Examples:
const NumberSchema = Type.Number();
// String to number conversion
const result1 = Value.Cast(NumberSchema, "123");
// Result: 123
const result2 = Value.Cast(NumberSchema, "invalid");
// Result: 0 (fallback for invalid conversion)
// Object casting
const User = Type.Object({
name: Type.String(),
age: Type.Number()
});
const userData = { name: "Alice", age: "25", extra: "ignored" };
const castUser = Value.Cast(User, userData);
// Result: { name: "Alice", age: 25 }Removes properties not defined in schema.
/**
* Removes properties not defined in schema
* @param schema - Schema defining allowed properties
* @param value - Value to clean
* @returns Value with only schema-defined properties
*/
function Clean<T extends TSchema>(schema: T, value: unknown): unknown;Usage Examples:
const User = Type.Object({
name: Type.String(),
age: Type.Number()
});
const dirtyData = {
name: "Alice",
age: 25,
password: "secret",
internal: true
};
const cleanData = Value.Clean(User, dirtyData);
// Result: { name: "Alice", age: 25 }Converts values to match schema requirements.
/**
* Converts values to match schema requirements
* @param schema - Target schema
* @param value - Value to convert
* @returns Converted value
*/
function Convert<T extends TSchema>(schema: T, value: unknown): Static<T>;Deep equality comparison for values.
/**
* Deep equality comparison for values
* @param left - First value
* @param right - Second value
* @returns True if values are deeply equal
*/
function Equal(left: unknown, right: unknown): boolean;Usage Examples:
const obj1 = { name: "Alice", tags: ["user", "admin"] };
const obj2 = { name: "Alice", tags: ["user", "admin"] };
const obj3 = { name: "Bob", tags: ["user"] };
console.log(Value.Equal(obj1, obj2)); // true
console.log(Value.Equal(obj1, obj3)); // false
// Works with nested objects and arrays
const nested1 = { user: { profile: { name: "Alice" } } };
const nested2 = { user: { profile: { name: "Alice" } } };
console.log(Value.Equal(nested1, nested2)); // trueGenerates hash codes for values.
/**
* Generates hash codes for values
* @param value - Value to hash
* @returns Hash code as number
*/
function Hash(value: unknown): number;Usage Examples:
const user1 = { name: "Alice", age: 25 };
const user2 = { name: "Alice", age: 25 };
const user3 = { name: "Bob", age: 30 };
const hash1 = Value.Hash(user1);
const hash2 = Value.Hash(user2);
const hash3 = Value.Hash(user3);
console.log(hash1 === hash2); // true (same content)
console.log(hash1 === hash3); // false (different content)Deep clones values with schema awareness.
/**
* Deep clones values with schema awareness
* @param value - Value to clone
* @returns Deep clone of value
*/
function Clone<T>(value: T): T;Usage Examples:
const original = {
user: { name: "Alice", tags: ["admin"] },
settings: { theme: "dark" }
};
const cloned = Value.Clone(original);
cloned.user.name = "Bob";
cloned.user.tags.push("user");
console.log(original.user.name); // "Alice" (unchanged)
console.log(original.user.tags); // ["admin"] (unchanged)
console.log(cloned.user.name); // "Bob"
console.log(cloned.user.tags); // ["admin", "user"]Mutates values using edit operations.
/**
* Mutates values using edit operations
* @param value - Value to mutate
* @param edits - Array of edit operations
* @returns Mutated value
*/
function Mutate(value: Mutable, edits: Edit[]): void;
interface Edit {
type: 'insert' | 'update' | 'delete';
path: string;
value?: unknown;
}
type Mutable<T = any> = { -readonly [K in keyof T]: T[K] };Usage Examples:
const data = { users: [{ name: "Alice" }, { name: "Bob" }] };
const edits = [
{ type: 'update', path: '/users/0/name', value: 'Alice Smith' },
{ type: 'insert', path: '/users/-', value: { name: 'Charlie' } },
{ type: 'delete', path: '/users/1' }
];
const result = Value.Mutate(data, edits);
// Result: { users: [{ name: "Alice Smith" }, { name: "Charlie" }] }Computes differences between values.
/**
* Computes differences between values
* @param left - Original value
* @param right - Modified value
* @returns Array of edit operations representing the difference
*/
function Diff(left: unknown, right: unknown): Edit[];Usage Examples:
const original = { name: "Alice", age: 25, city: "NYC" };
const modified = { name: "Alice Smith", age: 26 };
const diff = Value.Diff(original, modified);
// Result: [
// { type: 'update', path: '/name', value: 'Alice Smith' },
// { type: 'update', path: '/age', value: 26 },
// { type: 'delete', path: '/city' }
// ]Applies patches to values.
/**
* Applies patches to values
* @param value - Value to patch
* @param edits - Array of edit operations to apply
* @returns Patched value
*/
function Patch<T>(value: T, edits: Edit[]): T;Parses and validates values from JSON.
/**
* Parses and validates values from JSON
* @param schema - Schema to validate against
* @param value - JSON string or parsed value to validate
* @returns Parsed and validated value
* @throws ValueError if parsing or validation fails
*/
function Parse<T extends TSchema>(schema: T, value: string | unknown): Static<T>;Usage Examples:
const User = Type.Object({
name: Type.String(),
age: Type.Number()
});
// Parse from JSON string
const jsonString = '{"name":"Alice","age":25}';
const user1 = Value.Parse(User, jsonString);
// Result: { name: "Alice", age: 25 }
// Parse from object
const userObj = { name: "Bob", age: 30 };
const user2 = Value.Parse(User, userObj);
// Result: { name: "Bob", age: 30 }
// Throws on invalid data
try {
Value.Parse(User, '{"name":"Alice","age":"25"}'); // age is string
} catch (error) {
console.error("Parse failed:", error.message);
}Encodes values using schema transforms.
/**
* Encodes values using schema transforms
* @param schema - Transform schema
* @param value - Value to encode
* @returns Encoded value
*/
function Encode<T extends TSchema>(schema: T, value: Static<T>): unknown;Decodes transformed values to original form.
/**
* Decodes transformed values to original form
* @param schema - Transform schema
* @param value - Value to decode
* @returns Decoded value
*/
function Decode<T extends TSchema>(schema: T, value: unknown): Static<T>;Usage Examples:
// Transform that converts Date to/from ISO string
const DateTransform = Type.Transform(Type.String())
.Decode(value => new Date(value))
.Encode(value => value.toISOString());
const now = new Date();
const encoded = Value.Encode(DateTransform, now);
// Result: "2024-01-15T10:30:00.000Z"
const decoded = Value.Decode(DateTransform, encoded);
// Result: Date objectinterface ValueError extends Error {
type: ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
}
enum ValueErrorType {
ArrayContainsNonNumericIndex,
ArrayExpected,
ArrayItemMissing,
ArrayItemCountMinimum,
ArrayItemCountMaximum,
ArrayItemNotUnique,
BooleanExpected,
DateExpected,
FunctionExpected,
IntegerExpected,
LiteralValueExpected,
NeverExpected,
NullExpected,
NumberExpected,
ObjectExpected,
ObjectRequiredPropertyMissing,
ObjectAdditionalPropertiesNotPermitted,
ObjectPropertyCountMinimum,
ObjectPropertyCountMaximum,
StringExpected,
StringFormatInvalid,
StringLengthMinimum,
StringLengthMaximum,
StringPatternMismatch,
UnionExpected,
UndefinedExpected,
UnknownValue,
ValueCheckFailed
}
class ValueErrorIterator implements IterableIterator<ValueError> {
[Symbol.iterator](): IterableIterator<ValueError>;
next(): IteratorResult<ValueError>;
}
/**
* Returns iterator of validation errors
* @param schema - Schema to validate against
* @param value - Value to validate
* @returns Iterator of validation errors
*/
function Errors<T extends TSchema>(schema: T, value: unknown): ValueErrorIterator;Usage Examples:
const User = Type.Object({
name: Type.String({ minLength: 2 }),
age: Type.Number({ minimum: 0 }),
email: Type.String({ format: 'email' })
});
const invalidData = { name: "A", age: -5, email: "invalid-email" };
for (const error of Value.Errors(User, invalidData)) {
console.log(`${error.path}: ${error.message}`);
}
// Output:
// /name: String length minimum 2
// /age: Number minimum 0
// /email: String format 'email' invalidInstall with Tessl CLI
npx tessl i tessl/npm-sinclair--typebox