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

.pick() mask allowing non-present props when present props are defined #895

Closed
prescience-data opened this issue Jan 29, 2022 · 4 comments · Fixed by #3255
Closed

.pick() mask allowing non-present props when present props are defined #895

prescience-data opened this issue Jan 29, 2022 · 4 comments · Fixed by #3255
Labels
enhancement New feature or request wontfix This will not be worked on

Comments

@prescience-data
Copy link

prescience-data commented Jan 29, 2022

Example

// Original schema
const FooSchema = z.object({
  foo: z.string(),
  bar: z.string()
})


const CorrectlyFailingSchema = FooSchema.pick({
  notARealProperty: true // This causes TypeScript error as expected.
})


const IncorrectlyPassingSchema = FooSchema.pick({
  foo: true,
  notARealProperty: true // Once an existing property is added to the mask, any non-defined props can pass as well.
})

This became an issue today where after passing through a bundler (esbuild), a non-descriptive error started throwing on e.t._parse:

TypeError: Cannot read properties of undefined

The issue occurred because I had removed a property "title" from the original schema, but not from the pick() mask, so title._parse() was throwing as title was now undefined.

@noyan-alimov
Copy link
Contributor

Ideally typescript should cause an error.
I implemented to show a helpful error message.
Example schema:

const fish = z.object({
  name: z.string(),
  age: z.number(),
  nested: z.object({}),
});

And then:

fish.pick({ name: true, color: true })

Doing this should show color key does not exist in object schema. Available keys: name,age,nested

@prescience-data
Copy link
Author

Additional context:

image

@scotttrinh
Copy link
Collaborator

Ahh, nice find @prescience-data . This is due to how Mask is defined:

zod/src/types.ts

Line 1651 in d2ac69c

pick<Mask extends { [k in keyof T]?: true }>(

That means as long as it extends the shape it passes the type checker. I think there is a way to update this to require that all of the keys are valid keys from T. Feel free to submit a PR for this if you get around to it. Otherwise I'll take a swing at it soon.

@stale
Copy link

stale bot commented Apr 22, 2022

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request wontfix This will not be worked on
Projects
None yet
4 participants