Skip to content

Commit

Permalink
Merge pull request #13 from pandanoir/main
Browse files Browse the repository at this point in the history
change return type of $intersection
  • Loading branch information
mizchi authored Jul 9, 2023
2 parents 878893b + 7a9da8e commit 8eafc5d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
15 changes: 15 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,21 @@ test("union", () => {
expect($union([$string, $number])("")).toBe(true);
});

test("intersection", () => {
expect(
$intersection([
$object({ a: $number }, false),
$object({ b: $string }, false),
])({ a: 1, b: "" }),
).toBe(true);
expect(
$intersection([
$object({ a: $number }),
$object({ b: $string }),
])({ a: 1, b: "" }),
).toBe(false);
});

test("tuple", () => {
expect($tuple([$string])([""])).toBe(true);
expect($tuple([$string])(null)).toBe(false);
Expand Down
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ type TupleToIntersection<T extends any[]> = {
[I in keyof T]: (x: T[I]) => void;
}[number] extends (x: infer R) => void ? R : never;

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

export const $const =
<T extends number | string | boolean | undefined | void | symbol>(
def: T,
Expand Down Expand Up @@ -88,12 +92,12 @@ export const $enum =

export const $intersection = <Vs extends Array<Validator<any>>>(
validators: readonly [...Vs],
): Validator<Infer<TupleToIntersection<Vs>>> => {
): Validator<TupleToIntersection<MapInfer<Vs>>> => {
return ((
input: any,
ctx: ValidatorContext = { errors: [] },
path: (string | symbol | number)[] = [],
): input is Infer<TupleToIntersection<Vs>> => {
): input is TupleToIntersection<MapInfer<Vs>> => {
for (const validator of validators) {
if (!validator(input, ctx, path)) return false;
}
Expand Down

0 comments on commit 8eafc5d

Please sign in to comment.