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 of intersection of loose objects is invalid #12

Closed
pandanoir opened this issue Jun 28, 2023 · 1 comment · Fixed by #13
Closed

type of intersection of loose objects is invalid #12

pandanoir opened this issue Jun 28, 2023 · 1 comment · Fixed by #13

Comments

@pandanoir
Copy link
Contributor

pandanoir commented Jun 28, 2023

Problem

I used $intersection to define the types baseType & (typeA | typeB), but type inference does not work.

const baseType = $object({ common: $string }, false);
const typeA = $object({
    type: $const("a"),
    data: $number,
  }, false),
  typeB = $object({
    type: $const("b"),
    data: $string,
  }, false);

const validate = $intersection([$union([typeA, typeB]), baseType]); // expect: (typeA | typeB) & baseType
const x: Infer<typeof validate> = { type: "a", data: 42, common: "" }; // type error (because Infer<typeof validate> is {common: string})

validate itself is working as intended.

console.log(validate({ type: "a", data: 42, common: "" }) === true);
console.log(validate({ type: "b", data: "str", common: "" }) === true);

console.log(validate({ type: "a", data: 42 }) === false);
console.log(validate({ type: "a", data: "str", common: "" }) === false);
console.log(validate({ type: "b", data: 42, common: "" }) === false);

Expected Behavior

Infer<typeof validate> should be ({ type: 'a'; data: number } | { type: 'b'; data: string }) & { common: string }.

@pandanoir
Copy link
Contributor Author

pandanoir commented Jun 30, 2023

type MapInfer<T> = T extends [infer x, ...infer xs]
  ? [Infer<x>, ...MapInfer<xs>]
  : [];

export const $intersection = <Vs extends Validator<any>[]>(
  validators: readonly [...Vs]
): Validator<TupleToIntersection<MapInfer<Vs>>> => {

This code probably solves the problem. However, I'm worried that the breaking change to the $intersection type would not be a problem.

(type of intersection of exact objects is still invalid. $intersection([$object({ data: $number }), $object({ common: $string })]))

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.

1 participant