Is there a way to add extra options
after a type has been created
#697
-
I wish to add extra import { Type as t } from '@sinclair/typebox'
const S = t.String()
const S1 = t.MagicalExtend(S, { examples: ['home address']})
const S2 = t.MagicalExtend(S, {examples: ['date string']}) Is there a way to achieve this |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
@bhuynhdev Hi, TypeBox types just Json Schema objects, so you can just apply additional properties using the JavaScript spread operator. Below applies additional properties from T1 to T2, where we use import { Type as t } from '@sinclair/typebox'
const T1 = t.String() // const T1: TString = { type: 'string' }
const T2: typeof T1 = { foo: 'bar', ...T1 } // const T2: TString = { type: 'string', foo: 'bar' } So, the above applies to all TB types. You may wish to implement a function to make application of additional properties more consistent (where the options are applied before the schema to ensure no properties are overwritten). import { Type as t, TSchema } from '@sinclair/typebox'
export function MagicExtend<T extends TSchema>(schema: T, options: Record<PropertyKey, unknown>): T {
return { ...options, ...schema }
}
const T1 = t.String() // const T1: TString = { type: 'string' }
const T2 = MagicExtend(T1, { foo: 'bar' }) // const T2: TString = { type: 'string', foo: 'bar' } Hope this helps |
Beta Was this translation helpful? Give feedback.
@bhuynhdev Hi,
TypeBox types just Json Schema objects, so you can just apply additional properties using the JavaScript spread operator. Below applies additional properties from T1 to T2, where we use
typeof T1
to give a correct TSchema type of T2 (as they should be the same type)So, the above applies to all TB types. You may wish to implement a function to make application of additional properties more consistent (where the options are applied before the sche…