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

No coercion in intersection of unions #787

Closed
nicolabovolato opened this issue Mar 12, 2024 · 2 comments · Fixed by #791
Closed

No coercion in intersection of unions #787

nicolabovolato opened this issue Mar 12, 2024 · 2 comments · Fixed by #791

Comments

@nicolabovolato
Copy link

Hi,

I'm using Typebox 0.32.15 and this parse function, it looks like string coercion is not working properly when combining intersections and unions.

import { TSchema, Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';

const parse = <T extends TSchema>(T: T, value: unknown) =>
  Value.Decode(T, Value.Clean(T, Value.Default(T, Value.Convert(T, value))));

// OK
console.log(
  '1',
  parse(
    Type.Union([
      Type.Object({
        a: Type.Number(),
      }),
      Type.Object({
        b: Type.Number(),
      }),
    ]),
    { a: '1' }
  )
);
console.log(
  '2',
  parse(
    Type.Intersect([
      Type.Object({
        a: Type.Number(),
      }),
      Type.Object({
        c: Type.Number(),
      }),
    ]),
    { a: '1', c: '3' }
  )
);

// Fails
console.log(
  '3',
  parse(
    Type.Intersect([
      Type.Union([
        Type.Object({
          a: Type.Number(),
        }),
        Type.Object({
          b: Type.Number(),
        }),
      ]),
      Type.Object({
        c: Type.Number(),
      }),
    ]),
    {
      a: '1',
      c: '3',
    }
  )
);
@sinclairzx81
Copy link
Owner

@nicolabovolato Hi, Thanks for reporting!

Yes, this is a known limitation with TypeBox's current Convert logic. Looking at the code, I think it needs a review. Will investigate this when I next get some time to dig into the code, however keep in mind, a fix may take some time to implement (as intersection value handling is very complex and has been deferred a few times before, and there is a little bit of cross over with intersection handling elsewhere in the library which I'd like to take a look at also)

Will keep this issue open in the interim.
Thanks again!

@sinclairzx81
Copy link
Owner

@nicolabovolato Hi!

Hey, have pushed a fix for this on revision 0.32.16. The update should perform the intersected/union conversion, but just be mindful to always check the return value from Convert (as there are many cases where conversion may not be possible). If you experience any issues with the update, feel free to ping on this thread.

Thanks again for reporting!
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