Comments (3)
Yeah, you cannot do dynamic things (like call map
) to schemas because the types won't match up. This is just a little bit of safety that the TypeScript compiler provides since at runtime the compiler doesn't keep track of how you're updating your as const
array.
I definitely get wanting to improve the ergonomics here to avoid having to wrap each value in a literal but you have a few other options:
- Use an alias for
z.literal
to make it a little easier:const l = z.literal;
- Use a
z.custom
schema and provide the type explicitly:const unionLiterals = [0, 2, 5, 7] as const; const unionSchema = z.custom<(typeof unionLiterals)[number]>((v) => unionLiterals.includes(v), ); type UnionType = z.infer<typeof unionSchema>;
If it were me, I'd either just type out the z.literal(val)
syntax and just chalk it up to typing practice 😅 or use the custom schema if it's a really large array that I was copying from somewhere else (like an array of all locales, or country names, or something like that).
from zod.
While TypeScript doesn't support preserving tuple types when using Array.prototype.map
(see microsoft/TypeScript#29841), for this case we could define our own mapping function. I think something this could work for your initial question:
function zodLiteralUnion<T extends readonly [z.Primitive, z.Primitive, ...z.Primitive[]]>(
primitives: [...T]
) {
const literals = primitives.map(x => z.literal(x)) as {
[Index in keyof T]: z.ZodLiteral<T[Index]>
}
return z.union(literals)
}
// const A: z.ZodUnion<[z.ZodLiteral<1>, z.ZodLiteral<2>, z.ZodLiteral<3>]>
const A = z.union([z.literal(1), z.literal(2), z.literal(3)])
// type A = 2 | 1 | 3
type A = z.infer<typeof A>
// const B: z.ZodUnion<[z.ZodLiteral<1>, z.ZodLiteral<2>, z.ZodLiteral<3>]>
const B = zodLiteralUnion([1, 2, 3])
// type B = 2 | 1 | 3
type B = z.infer<typeof B>
from zod.
from zod.
Related Issues (20)
- z.union() inside of z.array repeats the same issue multiple times HOT 5
- Proposal: Ability to extract certain values from the validated objects while parsing
- z.date({ coerce: 'iso' })
- z.instanceOf error with class with private constructor
- Property 'pick' does not exist on type 'ZodType<Output, ZodTypeDef, Input>'. HOT 1
- IP Validation + optional is behaving unexpectedly HOT 2
- Support custom discriminators in `z.discriminatedUnion`
- CI lint checks can be simplified
- [Feature Request] take regular expressions to support progressive improvement
- [BUG] Generic Function with Object Extend/Merge not treating optional properties as optional and expecting them anyways. HOT 1
- refinement chains unexpectedly violate type safety HOT 1
- Infer new schema from parsed output
- Using nullable() or nullish() alone HOT 2
- Interest in codemods for migrating from v3 to v4?
- Recursive types with an intermediate object HOT 2
- Support `enumDescriptions`
- z.union() ignores custom error message HOT 1
- Extending zod schema with branded type produces typescript error
- z.string().base64() validation matches non-base64 strings
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from zod.