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

intersection flattens unions too much #1180

Open
Gelio opened this issue Apr 28, 2023 · 1 comment
Open

intersection flattens unions too much #1180

Gelio opened this issue Apr 28, 2023 · 1 comment

Comments

@Gelio
Copy link
Contributor

Gelio commented Apr 28, 2023

Because intersection uses UnionToIntersection on its arguments (except for the first one), it flattens any unions that appear in the intersection.

import * as s from "superstruct";
import { expectType, type TypeEqual } from "ts-expect";


const baseUnion = s.union([
    s.type({
        flavor: s.literal("a"),
    }),
    s.type({
        flavor: s.literal("b"),
        extraProperty: s.string(),
    }),
]);

const someOtherObject = s.type({
    foo: s.literal("bar")
});

const unionAsFirstInIntersection = s.intersection([
    baseUnion,
    someOtherObject,
]);

type ExpectedResult = ({ flavor: "a" } | { flavor: "b"; extraProperty: string }) & { foo: "bar" };

expectType<TypeEqual<s.Infer<typeof unionAsFirstInIntersection>, ExpectedResult>>(true);

const unionAsSecondInIntersection = s.intersection([
    someOtherObject,
    baseUnion,
]);

expectType<TypeEqual<s.Infer<typeof unionAsSecondInIntersection>, ExpectedResult>>(true); // error
expectType<TypeEqual<typeof unionAsSecondInIntersection, s.Struct<never, null>>>(false); // error

TypeScript playground

Notice that when baseUnion is used as the first in the intersection array, it works fine. When baseUnion appears second, UnionToIntesection flattens it too much, which causes the final unionAsSecondInIntersection struct to be never.

Workaround

Use union as the first element of the array provided to intersection. unionAsFirstInIntersection is constructed correctly.

@morlay
Copy link

morlay commented May 12, 2023

type IntersectionTypes<Types extends any[]> = Types extends [
    infer T,
    ...infer O
  ]
  ? T extends Struct<any, any>
    ? Infer<T> & IntersectionTypes<O>
    : unknown
  : unknown;
  

export function intersection<Types extends [...StructAny[]]>(
  ...types: Types
): Type<IntersectionTypes<Types>, null> {
  return ss.intersection(types as any) as any
}  

I fixed with this.

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

No branches or pull requests

2 participants