Comments (2)
I don't want to do this at the moment, since it would mark a subtle shift from being a "parse" tool into a "cast" tool. Casting gets messy quickly what with default values, required/non-required keys, recursive/cyclical types, primitive castings, etc. I always found yup/joi casting difficult to reason about.
I'd recommend building your own a default-setting + validation "pipeline" by combining Zod with something like lodash. You can use_.defaultsDeep()
to set defaults on an unvalidated object, like so:
import * as _ from 'lodash';
import * as z from "zod";
const dogDefaults = {
breed: "Unknown"
}
const Dog = z.object({
breed: z.string(),
age: z.number()
});
type Dog = z.TypeOf<typeof Dog>;
const unknownDog: any = { /* whatever */ };
const cleanAndValidate = (rawData: unknown)=>{
return Dog.parse(_.defaultsDeep(unknownDog, dogDefaults));
}
const validDog = cleanAndValidate(unknownDog);
// typeof validDog => Dog
from zod.
I would like to push defaults
feature into the zod.
zod is really nice tool, but it is hard to use it without the default values.
For example:
- There is the schema:
const LibrarySchema = z.object({
namespace: z.string().optional(),
components: z.record(
z.object({
names: z.string(),
}),
).optional(),
});
type ILibrarySchema = z.infer<typeof LibrarySchema>;
ILibrarySchema
equals to:
type ILibrarySchema = {
namespace?: string | undefined;
components?: Record<string, {
names: string;
}> | undefined;
}
so all fields are optional, as expected.
- Then I would like to fill schema with the default values
const parsed = LibrarySchema.parse(raw);
const config = withDefaults(parser);
Here is the problem. I can't correctly write the type for withDefaults
function.
const withDefaults = (config:ILibrarySchema): ??? => { ... };
It is not possible to return ILibrarySchema
since it has optional fields, but I would like to return config
with the default values, which means, that some fields should not be optional.
I expect defaults
to be:
const LibrarySchema = z.object({
namespace: z.string().optional().default('_'),
components: z.record(
z.object({
names: z.string(),
}),
).optional().default({}),
});
type ILibrarySchema = z.infer<typeof LibrarySchema>;
ILibrarySchema
to be:
type ILibrarySchema = {
namespace: string
components: Record<string, {
names: string;
}>;
}
cc @vriad
from zod.
Related Issues (20)
- PanelOn: z.coerce.boolean(), is generating an optional field PanelOn. How can we require it?
- .default() should apply default if wrapped schema transforms to undefined HOT 1
- Using the key of string enum using nativeEnum? HOT 2
- cuid validation HOT 1
- GitHub Stars links to NPM
- idea: leverage module augmentation to reduce bundle size
- Zod/ React Hook Form - Dynamic Field Array - Conditional Field HOT 3
- Recursive schema with lazy() doesn't seem to work
- required not work HOT 9
- Create an error map in pt-br
- .color() function to validate that a string is a valid color. HOT 1
- datetime validation fails if seconds are missing
- 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
- Use arrays to create unions HOT 3
- Support custom discriminators in `z.discriminatedUnion`
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.