sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.56k stars 148 forks source link

Composite Union type does not work #894

Closed pkuczynski closed 3 weeks ago

pkuczynski commented 1 month ago

I am defining my type as:

const pagination =  Type.Object({
  page: Type.Optional(Type.Number({  minimum: 1,  default: 1 })),
  size: Type.Optional(Type.Number({  minimum: 1,  default: 10 })),
})

const query = Type.Composite([
  pagination,
  Type.Union([
    Type.Object({
      categoryId: Type.Number()
    }),
    Type.Object({
      name: Type.String()
    })
])

and in the result I am getting:

 TObject<{
    page: TOptional<TNumber>
    size: TOptional<TNumber>
}>

like if it would be ignoring the Union part. What I was expecting to get as a JSON schema is (as in this example):

{
  type: "object",
  properties: { page: { type: "number" }, size: { type: "number" }},
  anyOf: [
    {
      required: ["categoryId"],
      properties: { categoryId: { type: "number" }}
    }
    {
      required: ["name"],
      properties: { name: { type: "string" }}
    }
  ]
}

This is important as otherwise the defaults in pagination would throw at ajv when strict: true is used (my initial attemp was to use Type.Union of Type.Composite from pagination and variant of other query params ).

I am using "@sinclair/typebox": "^0.32.31".

pkuczynski commented 1 month ago

As mentioned earlier, I tried with Type.Intersect instead of Type.Composite:

const query = Type.Intersect([
  pagination,
  Type.Union([
    Type.Object({
      categoryId: Type.Number()
    }),
    Type.Object({
      name: Type.String()
    })
])

Which compiles well, TS works well, but then ajv fails validation:

query = { categoryId: 10 }

must have required property 'name'
must match a schema in anyOf
sinclairzx81 commented 4 weeks ago

@pkuczynski Hi,

This is a known limitation that should be resolved in future revisions. You can work around this limitation by authoring the types slightly differently. As follows.

TypeScript Link Here

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

const Pagination = Type.Object({
  page: Type.Optional(Type.Number({  minimum: 1,  default: 1 })),
  size: Type.Optional(Type.Number({  minimum: 1,  default: 10 })),
})
const PaginationWithName = Type.Composite([Pagination, Type.Object({
  name: Type.String()
})])
const PaginationWithCategoryId = Type.Composite([Pagination, Type.Object({
  categoryId: Type.Number()
})])

type Query = Static<typeof Query>
const Query = Type.Union([
  PaginationWithName,
  PaginationWithCategoryId
])

What I was expecting to get as a JSON schema is (as in this example):

Unfortunately, the combination of object and anyOf (mixed as a singular schema as per your code snippet) falls outside the documented schematics generated by TypeBox. The preferred solution would be to have TypeBox automatically transform the schematics into the Query structure shown above. This would be analogous to the following TypeScript example.

TypeScript Link Here

interface Pagination {
    page?: number
    size?: number
}
// this is the shape you're asking to create
type Query = Pagination & (    
    { name: string } |         
    { categoryId: number }
)

// this is the shape typebox evaluates with Composite
type NonDistributedQuery = { [K in keyof Query]: Query[K] } // hover

// this is what typebox needs to do
type Evaluate<T> = { [K in keyof T]: T[K] } & {}

type DistributedQuery = Evaluate<Query> // hover

Above, the Evaluate<T> type will be added to TypeBox specifically for this case. The Evaluate function will take care of transforming the Intersect/Union into the flattened type DistributedUnion above. Unfortunately, this type isn't ready yet, so you will need to refactor the types shown in the previous example in the meantime.

Hope this helps S

sinclairzx81 commented 3 weeks ago

@pkuczynski Hi,

Might close up this issue for now as this issue is non-actionable on the current revision. In the interim, would recommend refactoring the types as follows.

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

const Pagination = Type.Object({
  page: Type.Optional(Type.Number({  minimum: 1,  default: 1 })),
  size: Type.Optional(Type.Number({  minimum: 1,  default: 10 })),
})
const PaginationWithName = Type.Composite([Pagination, Type.Object({
  name: Type.String()
})])
const PaginationWithCategoryId = Type.Composite([Pagination, Type.Object({
  categoryId: Type.Number()
})])

type Query = Static<typeof Query>
const Query = Type.Union([
  PaginationWithName,
  PaginationWithCategoryId
])

If you have any follow up questions on the above, feel free to reply on this thread.

All the best! S