bug: .transform() incorrectly changes ZodSchema
See original GitHub issuethe following snippet fails with error below. Adding a .transform
method to a zod schema will alter the input type, when it should be only be altering the output type. The output type seems to correctly be just number
.
import { z } from 'https://deno.land/x/zod@v3.2/mod.ts'
const percentage_parser = z.string().regex(/\d+%/).transform(str => parseFloat(str.slice(0, -1)) / 100)
function get_percentage(input: z.infer<typeof percentage_parser>) {
return percentage_parser.parse(input)
}
const result: number = get_percentage('100%')
error: TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'number'.
const result: number = get_percentage('100%')
here is a screenshot showing the full zod type declaration:
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (1 by maintainers)
Top Results From Across the Web
RFC: Refactoring transformers and Zod 3 · Issue #264 - GitHub
TLDR Transformers are poorly designed. I want to reimplement them but there will be breaking changes. Under this proposal, Zod 2 will never ......
Read more >Using Zod to Parse Function Schemas - hyper
We define a Zod schema for the adapter object. Then, given an adapter implementation, the port wraps each function implemented by the adapter ......
Read more >Why Zod 2 isn't leaving beta - Colin McDonnell
If the first argument is a function instead of a Zod schema, Zod should assume that the transformation doesn't transform the type. In...
Read more >Untitled
nativeEnum()`, which lets you create z Zod schema from an existing TypeScript `enum`: ... This is the result of a bug in the...
Read more >Newest 'zod' Questions - Stack Overflow
I have a zod schema that transforms a string (enum) value into an object. I want to use it with react-hook-forms and the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@andykais You can use
z.input
instead ofz.infer
. This works for arbitrarily complex schemas and disregards transforms at all levels of depth in your schema. This behavior is documented here: https://github.com/colinhacks/zod#what-about-transforms.That’s not exactly true. E.g. I want to input a number that is less than 5, I want a string but it should match a particular regex. There are tons of refinements that can be made which zod makes it easy to declare but that typescript cannot sufficiently express