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

.default() should apply default if wrapped schema transforms to undefined #3614

Open
jedwards1211 opened this issue Jul 3, 2024 · 1 comment · May be fixed by #3615
Open

.default() should apply default if wrapped schema transforms to undefined #3614

jedwards1211 opened this issue Jul 3, 2024 · 1 comment · May be fixed by #3615

Comments

@jedwards1211
Copy link

jedwards1211 commented Jul 3, 2024

This may seem strange, but it's because I've been dealing with AWS CloudFormation parameters, where you can only have empty strings, not null or undefined values...

I was trying to do

// helper used in place of `.optional()` for my schema for parsing CloudFormation metadata
function optional<T extends z.ZodTypeAny>(schema: T) {
  return z
    .union([z.literal('').transform(() => undefined), schema.optional()])
    .optional()
}

const parameter = optional(z.string()).default('test')

I expected parameter.parse('') to be 'test' but instead it's undefined. This violates the output type of .default('test'), so I think even if the input is defined, ZodDefault should check that the parse output is too.

@jedwards1211 jedwards1211 changed the title Should .default() parse with the wrapped schema and then check if the parsed value is undefined? .default() should apply default if wrapped schema's parse returns undefined Jul 3, 2024
@jedwards1211 jedwards1211 changed the title .default() should apply default if wrapped schema's parse returns undefined .default() should apply default if wrapped schema transforms to undefined Jul 3, 2024
@jedwards1211
Copy link
Author

Here we're seeing the consequence of designing ZodDefault to change the input to a default value if it's undefined, rather than just changing the output value if it's undefined.

To guarantee that ZodDefault does produce the correct output type, I had to:

  • Re-parse on the default value if parsing a non-null value output undefined
  • In the worst case, even parsing the default value outputs undefined -- I had to add an error for this case

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

Successfully merging a pull request may close this issue.

1 participant