Replies: 1 comment 1 reply
-
@cesxhin Hi, TypeBox enums are represented under the type system as a set of as Union values. TypeBox maps enums to the following representation. const T = { anyOf: [{ const: 'A' }, { const: 'B' }, { const: 'C' }] } ... however for presentation and documentation, most tooling expects const T = { enum: ['A', 'B', 'C'] } TypeBox is working towards supporting the second representation but it cannot currently as there are technical challenges supporting two Union-Like representations that describe the same thing. TypeBox chooses the It is possible to get this type presenting well, but you will need to create a custom type that builds the correct Json Schema representation. The following code does this with the custom type https://github.com/sinclairzx81/typebox/blob/master/example/prototypes/union-enum.ts import { TypeRegistry, Kind, TSchema, SchemaOptions, Static } from '@sinclair/typebox'
// -------------------------------------------------------------------------------------
// TUnionEnum
// -------------------------------------------------------------------------------------
export interface TUnionEnum<T extends (string | number)[]> extends TSchema {
[Kind]: 'UnionEnum'
static: T[number]
enum: T
}
// -------------------------------------------------------------------------------------
// UnionEnum
// -------------------------------------------------------------------------------------
/** `[Experimental]` Creates a Union type with a `enum` schema representation */
export function UnionEnum<T extends (string | number)[]>(values: [...T], options: SchemaOptions = {}) {
function UnionEnumCheck(schema: TUnionEnum<(string | number)[]>, value: unknown) {
return (typeof value === 'string' || typeof value === 'number') && schema.enum.includes(value)
}
if (!TypeRegistry.Has('UnionEnum')) TypeRegistry.Set('UnionEnum', UnionEnumCheck)
return { ...options, [Kind]: 'UnionEnum', enum: values } as TUnionEnum<T>
}
// ----------------
// Usage
// ----------------
enum Foo { A, B, C }
const E = UnionEnum([Foo.A, Foo.B, Foo.C]) // or UnionEnum(['A', 'B', 'C'])
type E = Static<typeof E> You can copy / paste this code into your project and use UnionEnum over Enum. As mentioned, TypeBox is working towards a more formal Hope this helps |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I have created an enum schema and would like to give an example of the value.
As per the image it doesn't even tell me the type of the field.
I also tried using Type.Union with Type.Literal but nothing changed.
I'm using fastify with swagger.
Is there something missing to set?
Thank you,
Cesxhin
Beta Was this translation helpful? Give feedback.
All reactions