Re-use your schema to derive the equivalent JSON Schema.
To install the .toJsonSchema
method on all schemas, simply import @traversable/schema-to-json-schema/install
.
Play with this example in the TypeScript playground.
import * as vi from 'vitest'
import { t } from '@traversable/schema'
import '@traversable/schema-to-json-schema/install'
// ↑↑ importing `@traversable/schema-to-json-schema/install` adds `.toJsonSchema` on all schemas
const schema_02 = t.intersect(
t.object({
stringWithMaxExample: t.optional(t.string.max(255)),
nestedObjectExample: t.object({
integerExample: t.integer,
tupleExample: t.tuple(
t.eq(1),
t.optional(t.eq(2)),
t.optional(t.eq(3)),
),
}),
stringOrNumberExample: t.union(t.string, t.number),
}),
t.object({
recordExample: t.record(t.string),
arrayExample: t.optional(t.array(t.string)),
enumExample: t.enum('x', 'y', 1, 2, null),
}),
)
vi.assertType<{
allOf: [
{
type: "object"
required: ("nestedObjectExample" | "stringOrNumberExample")[]
properties: {
stringWithMaxExample: { type: "string", minLength: 3 }
stringOrNumberExample: { anyOf: [{ type: "string" }, { type: "number" }] }
nestedObjectExample: {
type: "object"
required: ("integerExample" | "tupleExample")[]
properties: {
integerExample: { type: "integer" }
tupleExample: {
type: "array"
minItems: 1
maxItems: 3
items: [{ const: 1 }, { const: 2 }, { const: 3 }]
additionalItems: false
}
}
}
}
},
{
type: "object"
required: ("recordExample" | "enumExample")[]
properties: {
recordExample: { type: "object", additionalProperties: { type: "string" } }
arrayExample: { type: "array", items: { type: "string" } }
enumExample: { enum: ["x", "y", 1, 2, null] }
}
}
]
}>(schema_02.toJsonSchema())
// ↑↑ importing `@traversable/schema-to-json-schema` installs `.toJsonSchema`