ianstormtaylor / superstruct

A simple and composable way to validate data in JavaScript (and TypeScript).
https://docs.superstructjs.org
MIT License
6.95k stars 224 forks source link

Describe does not work well with union types #1229

Open BoveFabio opened 4 months ago

BoveFabio commented 4 months ago

Hi everyone,

I stumbled across a seemingly simple example where Describe does not work well with union. However, it might be I am missing something.

Consider the following:

type A = {
    a: "a";
};
type B = {
    b: "b";
};

const aStruct: Describe<A> = object({
    a: literal("a"),
});
const bStruct: Describe<B> = object({
    b: literal("b"),
});
const aorbStruct: Describe<A | B> = union([aStruct, bStruct]);

I would expect this to work. However, aorbStruct shows a TS error:

TS2322: Type Struct<A | B, null> is not assignable to type Describe<A | B>
  Types of property schema are incompatible. 
    Type null is not assignable to type
      {
        a: Describe<"a">; 
      } | {
        b: Describe<"b">;
      }

The strange thing is that it works once I include a primitive in the union:

const AorBorNumberStruct: Describe<A | B | number> = union([aStruct, bStruct, number()]);

works fine.

Could you please

Thank you!

amaral-ng commented 4 days ago

Same here, any news on the subject?

Node: v20.16.0 SuperStruct: v2.0.2