Supporting $ref in FromSchema #1180
-
Hello there! First of all, thanks for this great library! I found from-schema.ts which is perfect for my needs, as I have to parse multiple smaller JSON schemas and eventually compose them into new TypeBox models. Would it be possible to support Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@jrabausch Hi,
TypeBox has support for Additional Information on Modules Here import { Type, Static } from '@sinclair/typebox'
import { FromSchema } from './prototypes' // from prototypes
// Modules act as containers for multiple types. TypeBox
// uses modules to enable remote referential computations
// on types (which is very complex), but where the schema
// representation for computation is expressed as `$defs`
// and `$ref` schematics.
const Module = Type.Module({
// dependencies
A: FromSchema({ type: 'boolean' } as const),
B: FromSchema({ type: 'string' } as const),
C: FromSchema({ type: 'number' } as const),
// dependant
T: FromSchema({
type: 'object',
required: ['a', 'b', 'c'],
properties: {
a: { $ref: 'A' },
b: { $ref: 'B' },
c: { $ref: 'C' }
}
} as const)
})
const T = Module.Import('T')
// where T is:
//
// const T = {
// '$defs': {
// A: { type: 'boolean', '$id': 'A' },
// B: { type: 'string', '$id': 'B' },
// C: { type: 'number', '$id': 'C' },
// T: {
// type: 'object',
// required: [ 'a', 'b', 'c' ],
// properties: {
// a: { '$ref': 'A' },
// b: { '$ref': 'B' },
// c: { '$ref': 'C' }
// },
// '$id': 'T'
// }
// },
// '$ref': 'T' // entry
// }
type T = Static<typeof T>
// type T = {
// a: boolean;
// b: string;
// c: number;
// } I'm not sure if the above would be exactly ideal for your use case (combining FromSchema with Module is somewhat arcane, but possible). Users who need If you can provide a bit more insight into what you need, or how you need to layout the definitions, I may be able to provide some additional help. Let me know |
Beta Was this translation helpful? Give feedback.
@jrabausch Hi,
TypeBox has support for
$ref
and$defs
schematics via Type.Module. However be mindful that Modules are very constrained and may not be suitable for all cases. Below is how you might approach creating definition schematics (using FromSchema (which I've just pushed an update for to handle$ref
, so be sure to grab the latest prototype))Additional Information on Modules Here