From 81d2e894c7813066173da4a716320b9fcf08e6c8 Mon Sep 17 00:00:00 2001 From: Colin McDonnell Date: Tue, 16 Apr 2024 15:19:30 -0700 Subject: [PATCH] Make required and partial more typesafe --- deno/lib/__tests__/pickomit.test.ts | 16 ++++++++++++++++ deno/lib/types.ts | 4 ++-- src/__tests__/pickomit.test.ts | 16 ++++++++++++++++ src/types.ts | 4 ++-- 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/deno/lib/__tests__/pickomit.test.ts b/deno/lib/__tests__/pickomit.test.ts index f89b01253..db973267a 100644 --- a/deno/lib/__tests__/pickomit.test.ts +++ b/deno/lib/__tests__/pickomit.test.ts @@ -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 }); +}); diff --git a/deno/lib/types.ts b/deno/lib/types.ts index 42cada03a..bba304357 100644 --- a/deno/lib/types.ts +++ b/deno/lib/types.ts @@ -2736,7 +2736,7 @@ export class ZodObject< UnknownKeys, Catchall >; - partial( + partial>( mask: Mask ): ZodObject< objectUtil.noNever<{ @@ -2769,7 +2769,7 @@ export class ZodObject< UnknownKeys, Catchall >; - required( + required>( mask: Mask ): ZodObject< objectUtil.noNever<{ diff --git a/src/__tests__/pickomit.test.ts b/src/__tests__/pickomit.test.ts index d1432c85d..134d03954 100644 --- a/src/__tests__/pickomit.test.ts +++ b/src/__tests__/pickomit.test.ts @@ -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 }); +}); diff --git a/src/types.ts b/src/types.ts index 37992abdb..98db0c8a0 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2736,7 +2736,7 @@ export class ZodObject< UnknownKeys, Catchall >; - partial( + partial>( mask: Mask ): ZodObject< objectUtil.noNever<{ @@ -2769,7 +2769,7 @@ export class ZodObject< UnknownKeys, Catchall >; - required( + required>( mask: Mask ): ZodObject< objectUtil.noNever<{