Skip to content

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

@justinsmid

Description

@justinsmid

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions