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

omit & pick allowing keys not present in the object #2607

Open
justinsmid opened this issue Jul 26, 2023 · 1 comment
Open

omit & pick allowing keys not present in the object #2607

justinsmid opened this issue Jul 26, 2023 · 1 comment

Comments

@justinsmid
Copy link

justinsmid commented Jul 26, 2023

It seems that z.omit and z.pick allow any keys to be omitted/picked, as long as one of the omitted/picked keys is in the object.

import { z } from "zod"

export const SomeZodObject = z.object({
  a: z.string(),
  b: z.string(),
})

export const ErroneousOmit = SomeZodObject.omit({
  c: true, // <-- Errors because `c` is not in `SomeZodObject`, and it is the only key being omitted
})

export const AllowedOmit = SomeZodObject.omit({
  a: true,
  c: true, // <-- Does *not* error because `a` *is*` part of `SomeZodObject`, so any key is now allowed
})

The same behavior as above happens with pick.

Note that TypeScript's Omit type does allow omitting keys not present in the object:

type SomeZodObjectInput = z.input<typeof SomeZodObject>

// No errors
export type TSOmitted1 = Omit<SomeZodObjectInput, "c">
export type TSOmitted2 = Omit<SomeZodObjectInput, "a" | "c">

But TypeScript's Pick type does not:

type SomeZodObjectInput = z.input<typeof SomeZodObject>

// Both of these error
export type TSPicked1 = Pick<SomeZodObjectInput, "c">
export type TSPicked2 = Pick<SomeZodObjectInput, "a" | "c">

Is this intended behavior? And if so, is there a way to get TS to error for any key that doesn't exist in the object?

TSPlayground: https://tsplay.dev/wO1pdm

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