Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type.Required with a union generates the wrong type for a non object type #1169

Closed
ianfireman opened this issue Feb 13, 2025 · 1 comment · Fixed by #1171
Closed

Type.Required with a union generates the wrong type for a non object type #1169

ianfireman opened this issue Feb 13, 2025 · 1 comment · Fixed by #1171

Comments

@ianfireman
Copy link

When using a union that contains a non object(ex: Type.String, Type.Number, Type.Array) inside it and passing this union to a Type.Required it converts the type to a empty object.

How to reproduce:
Create a union type:

export const exampleUnionSchema = Type.Union([
    Type.String(), // it could be a Number, Array and the same error happens
    Type.Object({
        type: Type.Literal('text'),
        text: Type.String(),
    }),
])

Use the union type in a field using the Type.Required:

export const requiredUsingUnionSchema = Type.Object({
    content: Type.Required(exampleUnionSchema),
})

The schema generated is:

(property) content: TUnion<[TObject<{}>, TObject<{
    type: TLiteral<"text">;
    text: TString;
}>]>

But I think it should be:

(property) content: TUnion<[TString, TObject<{
    type: TLiteral<"text">;
    text: TString;
}>]>

Typebox version: 0.34.13
System: MacOS 14.5

@sinclairzx81
Copy link
Owner

@ianfireman Hi, thanks for reporting

Yes, I agree. This was a good find. I have published an update on 0.34.22 that should resolve the issue.

TypeScript Link Here

import { Syntax } from '@sinclair/typebox/syntax'
import { Static } from '@sinclair/typebox'

// types

const exampleUnionSchema = Syntax(`string | { type: 'text', text: string }`)

const partialContent = Syntax({ exampleUnionSchema }, `Partial<exampleUnionSchema>`)

const requiredContent = Syntax({ partialContent }, `Required<partialContent>`)

// inference

type partialContent = Static<typeof partialContent>

//   ^ (string | { type?: 'text' | undefined, text?: string | undefined })

type requiredContent = Static<typeof requiredContent> 

//   ^ (string | { type: 'text', text: string })

The PR auto closed out this issue, but if you have any problems with the update, feel free to ping on this thread.
Cheers
S

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants