Closed Jazcash closed 1 month ago
@Jazcash Hi,
TypeBox doesn't provide any facilitates for $defs
currently (this is something you will need to structure yourself). However cross referencing types with 'string' arguments is generally recommended (as this translates directly to $ref: '...'
schematics). However you can do a better job with typing the reference using the following scheme.
import { Type, Static } from '@sinclair/typebox'
const name = Type.String({ $id: "name" })
const person = Type.Object({
// infers as TString. $ref string specific to target location in $defs
name: Type.Ref<typeof name>('#/definitions/name'),
}, { $id: 'person' })
const schema = {
$defs: {
name
},
anyOf: [
person
],
} as const
type T = Static<typeof person> // type T = { name: 'string' }
Hope this helps S
I have some shared types that are reused in multiple places throughout my whole schema and I wish to reference them using
Ref
, however I don't know how to instruct TypeBox to declare my shared types asdefinitions
or$defs
in a way that the generated refs work properly. I'm mainly trying to figure this out because I'm usingjson-schema-to-typescript
to generated.ts
files (because I don't want TypeBox src in the output), and that library expects local definitions to be referenced using patterns such as#/definitions/name
.e.g.
Causes an error because the final schema has
"$ref": "name"
, whichjson-schema-to-typescript
has no idea how to resolve, I think because local refs must start with#
, and anything else it tries to resolve externally?So if I change
Type.Ref(name)
toType.Ref("#/$defs/name")
it works just fine, but then I lose the nice coupling and have hardcoded ref strings that are awkward to maintain manually, but doing this correctly generates:Is there a better way of achieving this?