Re-use your schema to derive a super fast validation function (with even faster compiled validators coming soon!)
.validate
is similar to z.safeParse
, except more than an order of magnitude faster*.
.validate
method to all schemas, all you need to do is import @traversable/schema-to-validator
.Play with this example in the TypeScript playground.
import { t } from '@traversable/schema'
import '@traversable/schema-to-validator'
let schema_01 = t.object({
product: t.object({
x: t.integer,
y: t.integer
}),
sum: t.union(
t.tuple(t.eq(0), t.integer),
t.tuple(t.eq(1), t.integer),
),
})
let result = schema_01.validate({ product: { x: null }, sum: [2, 3.141592]})
// ↑↑ importing `@traversable/schema-to-validator` installs `.validate`
console.log(result)
// =>
// [
// { "kind": "TYPE_MISMATCH", "path": [ "product", "x" ], "expected": "number", "got": null },
// { "kind": "REQUIRED", "path": [ "product" ], "msg": "Missing key 'y'" },
// { "kind": "TYPE_MISMATCH", "path": [ "sum", 0 ], "expected": 0, "got": 2 },
// { "kind": "TYPE_MISMATCH", "path": [ "sum", 1 ], "expected": "number", "got": 3.141592 },
// { "kind": "TYPE_MISMATCH", "path": [ "sum", 0 ], "expected": 1, "got": 2 },
// { "kind": "TYPE_MISMATCH", "path": [ "sum", 1 ], "expected": "number", "got": 3.141592 },
// ]