Re-use your schema to derive a bi-directional codec (with compiled codecs coming soon!)
-
Instructions: to install the
.codec
method on all schemas, all you need to do is import@traversable/derive-codec
.- To create a covariant codec (similar to zod's
.transform
), use.codec.pipe
- To create a contravariant codec (similar to zod's
.preprocess
), use.codec.extend
(WIP)
- To create a covariant codec (similar to zod's
Play with this example in the TypeScript playground.
import { t } from '@traversable/schema'
import '@traversable/derive-codec'
// ^^ this installs the `.pipe` and `.extend` methods on all schemas
let User = t
.object({ name: t.optional(t.string), createdAt: t.string }).codec // <-- notice we're pulling off the `.codec` property
.pipe((user) => ({ ...user, createdAt: new Date(user.createdAt) }))
.unpipe((user) => ({ ...user, createdAt: user.createdAt.toISOString() }))
let fromAPI = User.parse({ name: 'Bill Murray', createdAt: new Date().toISOString() })
// ^? let fromAPI: Error | { name?: string, createdAt: Date}
if (fromAPI instanceof Error) throw fromAPI
fromAPI
// ^? { name?: string, createdAt: Date }
let toAPI = User.encode(fromAPI)
// ^? let toAPI: { name?: string, createdAt: string }