vērāx — truthful
Runtime types for TypeScript. Zero dependencies; every schema is a Standard Schema.
bun add verax
TypeScript 7+, ESM only, Node ≥24. Every example runs: edit one, press ▶ or ⌘↵. The test suite runs them too, so each output shown is what verax prints.
Start
A schema is a value and a type. parse returns the data or
throws; validate returns every issue, with its path.
import { type Infer, int, list, nullable, object, parse, string, validate } from 'verax';
const User = object('User', {
age: nullable(int()),
name: string(),
tags: list(string()),
});
type User = Infer<typeof User>;
const ada: User = parse({ age: 36, name: 'Ada', tags: ['math'] }, User);
console.log(ada);
console.log(validate({ age: 1.5, tags: [1] }, User));
{ age: 36, name: 'Ada', tags: ['math'] }
{
issues: [
{ message: 'Expected Int | null, received 1.5', path: ['age'] },
{ message: 'Expected String, missing', path: ['name'] },
{ message: 'Expected String, received 1', path: ['tags', 0] },
],
}
Types
int is signed 32-bit, float finite,
id a string.
import { boolean, enums, float, id, is, literal, optional, record, scalar, tuple, unknown } from 'verax';
const Role = enums('Role', ['ADMIN', 'MEMBER']);
const Email = scalar('Email', (v): v is string => typeof v === 'string' && v.includes('@'));
console.log({
int: is(2 ** 31, int()),
float: is(0.1, float()),
id: is('42', id()),
boolean: is(false, boolean()),
enums: is('ADMIN', Role),
scalar: is('ada@example.com', Email),
literal: is('post', literal('post')),
unknown: is(Symbol('any'), unknown()),
});
{
int: false,
float: true,
id: true,
boolean: true,
enums: true,
scalar: true,
literal: true,
unknown: true,
}
Every field is non-null unless wrapped: nullable may be
null, optional may be absent.
record checks every value under any key;
tuple an array of exactly its items, each by its own schema.
const Patch = object({ bio: nullable(string()), nick: optional(string()) });
const Scores = record(int());
const Point = tuple([float(), float()]);
console.log({
bioNull: is({ bio: null }, Patch),
bioMissing: is({}, Patch),
scores: is({ ada: 3, lin: 5 }, Scores),
scoreString: is({ ada: 3, lin: '5' }, Scores),
point: is([0.5, 2], Point),
pointLong: is([0.5, 2, 1], Point),
});
{
bioNull: true,
bioMissing: false,
scores: true,
scoreString: false,
point: true,
pointLong: false,
}
Objects
An object is exact: an unknown key is an issue. Its name emits
it in SDL and names it in errors. A recursive one makes the field a getter and states its
type, which TypeScript cannot infer through a cycle.
import type { Schema } from 'verax';
console.log(validate({ admin: true, age: null, name: 'Ada', tags: [] }, User).issues);
type Comment = {
replies: Comment[];
text: string;
};
const Comment: Schema<Comment> = object('Comment', {
get replies() {
return list(Comment);
},
text: string(),
});
console.log(is({ replies: [{ replies: [], text: 'yes' }], text: 'ok?' }, Comment));
[{ message: 'Unknown field on User', path: ['admin'] }]
true
Unions
Tag members with __typename: one read of the tag picks the
member. A failed union explains itself, by the member its tag names or, untagged, by the
closest one.
import { union } from 'verax';
const Ping = object('Ping', { __typename: literal('Ping'), at: int() });
const Track = object('Track', { __typename: literal('Track'), event: string() });
const Message = union('Message', [Ping, Track]);
console.log(validate({ __typename: 'Track', event: 7 }, Message).issues);
console.log(validate({ __typename: 'Pong' }, Message).issues);
const Contact = union('Contact', [object({ email: Email }), object({ phone: string() })]);
console.log(validate({ email: 'ada' }, Contact).issues);
[{ message: 'Expected String, received 7', path: ['event'] }]
[
{
message: 'Expected "Ping" | "Track", received "Pong"',
path: ['__typename'],
},
]
[{ message: 'Expected Email, received "ada"', path: ['email'] }]
Verbs
| verb | gives |
|---|---|
is(value, S) |
a type guard to Input<typeof S>; builds nothing
|
assert(value, S) |
the same, or throws VeraxError with every issue |
validate(value, S) |
{ value } or { issues }; never
throws
|
parse(value, S) |
Infer<typeof S>, or throws
VeraxError
|
is and assert check through
coerce but leave the input as it was;
validate and parse return the
converted output.
import { VeraxError, assert, coerce } from 'verax';
const Count = coerce(int(), (v) => (typeof v === 'string' ? Number(v) : v));
console.log({ is: is('3', Count), parse: parse('3', Count), validate: validate('three', Count) });
try {
assert({ name: 'Ada' }, User);
} catch (error) {
console.log(error instanceof VeraxError, String(error));
}
{
is: true,
parse: 3,
validate: { issues: [{ message: 'Expected Int, received NaN', path: [] }] },
}
true VeraxError: age: Expected Int | null, missing
tags: Expected list, missing
refine · coerce
refine narrows the accepted values and keeps the type.
coerce converts before validating: defaults, strings, dates.
import { refine } from 'verax';
const Adult = refine(int(), 'Expected an adult', (n) => n >= 18);
const Page = coerce(optional(int()), (v) => v ?? 1);
const When = coerce(
scalar('DateTime', (v): v is Date => v instanceof Date && !Number.isNaN(v.getTime())),
(v) => (typeof v === 'string' ? new Date(v) : v),
);
console.log({
adult: validate(17, Adult),
page: parse(undefined, Page),
when: parse('2026-10-01', When),
});
{
adult: { issues: [{ message: 'Expected an adult', path: [] }] },
page: 1,
when: 2026-10-01T00:00:00.000Z,
}
Use cases
Control flow
const handle = (data: unknown): string => {
if (is(data, Ping)) return `pong ${data.at}`;
assert(data, Track);
return `tracked ${data.event}`;
};
console.log(handle({ __typename: 'Ping', at: 1 }), handle({ __typename: 'Track', event: 'open' }));
pong 1 tracked open
Fetch bodies
The output is a fresh plain object: no getter, proxy or prototype of the input reaches it.
const response = new Response('{"age":null,"name":"Lin","tags":["c"]}');
console.log(parse(await response.json(), User));
{ age: null, name: 'Lin', tags: ['c'] }
Form data
Form values are strings and an unchecked box is absent: coerce each field, and leave a blank one to fail.
const Signup = object('Signup', {
age: coerce(int(), (v) => (typeof v === 'string' && v.trim() !== '' ? Number(v) : v)),
email: Email,
newsletter: coerce(boolean(), (v) => v === 'on'),
});
const form = new FormData();
form.set('age', '36');
form.set('email', 'ada@example.com');
console.log(parse(Object.fromEntries(form.entries()), Signup));
form.set('age', '');
console.log(validate(Object.fromEntries(form.entries()), Signup).issues);
{ age: 36, email: 'ada@example.com', newsletter: false }
[{ message: 'Expected Int, received ""', path: ['age'] }]
Object.fromEntries keeps only the last value of a repeated key:
group with getAll, and default the list no field sent.
const Upload = object({
files: list(scalar('File', (v): v is File => v instanceof File)),
tags: coerce(list(string()), (v) => v ?? []),
});
const many = new FormData();
many.append('files', new File(['hi'], 'hi.txt'));
many.append('tags', 'a');
many.append('tags', 'b');
const grouped = Object.fromEntries(
Array.from(new Set(many.keys()), (key) => [key, many.getAll(key)]),
);
const upload = parse(grouped, Upload);
console.log(upload.files.map((file) => file.name), upload.tags, parse({ files: [] }, Upload));
['hi.txt'] ['a', 'b'] { files: [], tags: [] }
Tests
In bun:test or node:test,
assert is the assertion: a failure throws and the runner prints
every issue.
test('GET /users/1', async () => {
assert(await (await fetch('/users/1')).json(), User);
});
Standard Schema
Hand any schema to a library that speaks it: tRPC, Hono, TanStack Form.
console.log(await User['~standard'].validate({ age: null, name: 'Ada', tags: [] }));
{ value: { age: null, name: 'Ada', tags: [] } }
SDL
sdl() prints GraphQL SDL for every named type its roots reach;
__typename stays implicit. It throws on an unnamed type and on
SDL that would lie.
import { sdl } from 'verax/sdl';
console.log(sdl([User, Comment, Message]));
type Comment {
replies: [Comment!]!
text: String!
}
union Message = Ping | Track
type Ping {
at: Int!
}
type Track {
event: String!
}
type User {
age: Int
name: String!
tags: [String!]!
}
With { input: true } it emits
input types, for arguments.
console.log(sdl([Signup], { input: true }));
scalar Email
input Signup {
age: Int!
email: Email!
newsletter: Boolean!
}
Guarantees
Validation never throws and never returns a wrong verdict. A throwing callback, hostile
getter or exhausted stack is an issue, and every limit fails closed: nesting past 512 is
Too deep, work past 10 million steps
Too complex, and issues stop at 100. The
contract states each limit exactly.
const hostile = {
age: null,
get name(): string {
throw new Error('boom');
},
tags: [],
};
console.log(validate(hostile, User).issues);
let deep: Comment = { replies: [], text: '' };
for (let level = 0; level < 600; level += 1) deep = { replies: [deep], text: '' };
console.log(validate(deep, Comment).issues?.map(({ message }) => message));
[{ message: 'Threw: boom', path: ['name'] }]
['Too deep']