@bemoje/tschema
v2.0.0
Published
TypeScript schema validation utilities based on TypeBox.
Maintainers
Readme
@mono/tschema
TypeScript schema validation utilities based on TypeBox.
Exports
- SchemaValidationError: Error thrown when a value does not match a given schema. Contains an array of ValueError instances with details about each violation.
- assertValidSchema: Asserts that data conforms to a TypeBox schema, throwing a SchemaValidationError if it doesn't.
Usage
Assertion & Validation
Assert that unknown data conforms to a TypeBox schema. Throws a structured validation error containing individual violation details.
import { Type } from '@sinclair/typebox'
import { assertValidSchema, SchemaValidationError } from '@mono/tschema'
const userSchema = Type.Object({ name: Type.String(), age: Type.Number() })
const data = { name: 'Alice', age: 'thirty' }
try {
assertValidSchema(userSchema, data, 'Invalid user data')
} catch (error) {
if (error instanceof SchemaValidationError) {
console.error(error.message) // 'Invalid user data'
console.error(error.value) // The originally validated object
console.error(error.errors) // Array of specific TypeBox ValueErrors
}
}