sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.77k stars 152 forks source link

Given a type, convert it to Typebox #796

Closed cybercoder-naj closed 5 months ago

cybercoder-naj commented 5 months ago

I may be blind, but is there a way we can convert a type to Tybebox, like z.Schema() from zod?

sinclairzx81 commented 5 months ago

@cybercoder-naj Hi,

I'm not sure what z.Schema() does (i can't find mention of it in the Zod documentation). TypeBox doesn't support direct conversion from TS type to TypeBox type (as TS types are erased by the compiler). However TypeBox does provide some offline tools to transform TS types to X types.

https://sinclairzx81.github.io/typebox-workbench

https://github.com/sinclairzx81/typebox-codegen

Is this what you mean?

sinclairzx81 commented 5 months ago

@cybercoder-naj Hiya

Hey, might close off this issue as (if I understand correctly), there isn't a way to convert a TS type into a TypeBox type unless you use code transforms (see links above). Also, I can't find any information on z.Schema(), but if this function returns something like Json Schema....All TypeBox types are Json Schema by default.

import { Type, type Static } from '@sinclair/typebox'

const T = Type.Object({                              // const T = {
  x: Type.Number(),                                  //   type: 'object',
  y: Type.Number(),                                  //   required: ['x', 'y', 'z'],
  z: Type.Number()                                   //   properties: {
})                                                   //     x: { type: 'number' },
                                                     //     y: { type: 'number' },
                                                     //     z: { type: 'number' }
                                                     //   }
                                                     // }

type T = Static<typeof T>                            // type T = {
                                                     //   x: number,
                                                     //   y: number,
                                                     //   z: number
                                                     // }

Feel free to ping this thread if any have any follow up questions, or can clarify what is meant by "converting a type to typebox type". There's quite a few ways TypeBox can transform types at runtime, but need specifics to provide more detail.

All the best! S