Skip to content

Commit

Permalink
Make required and partial more typesafe
Browse files Browse the repository at this point in the history
  • Loading branch information
colinhacks committed Apr 16, 2024
1 parent 96510ab commit 81d2e89
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 4 deletions.
16 changes: 16 additions & 0 deletions deno/lib/__tests__/pickomit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,19 @@ test("nonstrict parsing - fail", () => {
const bad = () => laxfish.parse({ whatever: "asdf" } as any);
expect(bad).toThrow();
});

test("pick/omit/required/partial - do not allow unknown keys", () => {
const schema = z.object({
name: z.string(),
age: z.number(),
});

// @ts-expect-error
schema.pick({ $unknown: true });
// @ts-expect-error
schema.omit({ $unknown: true });
// @ts-expect-error
schema.required({ $unknown: true });
// @ts-expect-error
schema.partial({ $unknown: true });
});
4 changes: 2 additions & 2 deletions deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2736,7 +2736,7 @@ export class ZodObject<
UnknownKeys,
Catchall
>;
partial<Mask extends { [k in keyof T]?: true }>(
partial<Mask extends util.Exactly<{ [k in keyof T]?: true }, Mask>>(
mask: Mask
): ZodObject<
objectUtil.noNever<{
Expand Down Expand Up @@ -2769,7 +2769,7 @@ export class ZodObject<
UnknownKeys,
Catchall
>;
required<Mask extends { [k in keyof T]?: true }>(
required<Mask extends util.Exactly<{ [k in keyof T]?: true }, Mask>>(
mask: Mask
): ZodObject<
objectUtil.noNever<{
Expand Down
16 changes: 16 additions & 0 deletions src/__tests__/pickomit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,19 @@ test("nonstrict parsing - fail", () => {
const bad = () => laxfish.parse({ whatever: "asdf" } as any);
expect(bad).toThrow();
});

test("pick/omit/required/partial - do not allow unknown keys", () => {
const schema = z.object({
name: z.string(),
age: z.number(),
});

// @ts-expect-error
schema.pick({ $unknown: true });
// @ts-expect-error
schema.omit({ $unknown: true });
// @ts-expect-error
schema.required({ $unknown: true });
// @ts-expect-error
schema.partial({ $unknown: true });
});
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2736,7 +2736,7 @@ export class ZodObject<
UnknownKeys,
Catchall
>;
partial<Mask extends { [k in keyof T]?: true }>(
partial<Mask extends util.Exactly<{ [k in keyof T]?: true }, Mask>>(
mask: Mask
): ZodObject<
objectUtil.noNever<{
Expand Down Expand Up @@ -2769,7 +2769,7 @@ export class ZodObject<
UnknownKeys,
Catchall
>;
required<Mask extends { [k in keyof T]?: true }>(
required<Mask extends util.Exactly<{ [k in keyof T]?: true }, Mask>>(
mask: Mask
): ZodObject<
objectUtil.noNever<{
Expand Down

0 comments on commit 81d2e89

Please sign in to comment.