Documentation
Start with a literal.
A litetype schema is either a leaf such as string, or a plain object whose values are schemas. That is the whole model.
npm i litetype
import { string, number, type Infer, parse } from 'litetype'
const User = {
name: string.min(1),
age: number.min(0),
'email?': string.email(),
}
type User = Infer<typeof User>
const user = parse(User, input)
Choose a validation verb
| Job | Use |
|---|---|
| Return data or throw | parse(schema, input) |
| Return a result union | safeParse(schema, input) |
| Narrow an unknown value | check(schema, input) |
| Predicate for a hot loop | compile(schema) |
Schemas compile automatically on first use. Call compile only when a hot loop should avoid the cache lookup.
Optional key ≠ undefined value
import { string } from 'litetype'
const A = { 'bio?': string } // bio may be omitted
const B = { bio: string.undefinable() } // bio is required, value may be undefined
The trailing ? mirrors a TypeScript optional property. It belongs to the key. Nullability belongs to the value.
Object policy is explicit
import { parse, strict, string, strip } from 'litetype'
parse({ name: string }, input) // keep extra keys, no copy
parse(strip({ name: string }), input) // remove extra keys
parse(strict({ name: string }), input) // reject extra keys
Forms: map, then check
import { coerce, parse, preprocess, string } from 'litetype'
parse(preprocess(v => v === '' ? undefined : v, string.undefinable()), '')
parse(coerce.number(), '42') // 42