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

Add mask parameter to .required method #1315

Merged
merged 3 commits into from Oct 5, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Expand Up @@ -925,6 +925,42 @@ const deepPartialUser = user.deepPartial();

> Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.


### `.required`

Contrary to the `.partial` method, the `.required` method makes all properties required.

Starting from this object:

```ts
const user = z.object({
email: z.string()
username: z.string(),
}).partial();
// { email?: string | undefined; username?: string | undefined }
```

We can create a required version:

```ts
const requiredUser = user.required();
// { email: string; username: string }
```

You can also specify which properties to make required:

```ts
const requiredEmail = user.required({
email: true,
});
/*
{
email: string;
username?: string | undefined;
}
*/
```

### `.passthrough`

By default Zod object schemas strip out unrecognized keys during parsing.
Expand Down
37 changes: 37 additions & 0 deletions deno/lib/README.md
Expand Up @@ -328,6 +328,7 @@ There are a growing number of tools that are built atop or support Zod natively!
- [`zod-xlsx`](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas.
- [`remix-domains`](https://github.com/SeasonedSoftware/remix-domains/): Improves end-to-end type safety in [Remix](https://remix.run/) by leveraging Zod to parse the framework's inputs such as FormData, URLSearchParams, etc.
- [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod.
- [`@runtyping/zod`](https://github.com/johngeorgewright/runtyping/tree/master/packages/zod): Generate zod from static types & JSON schema.

#### Form integrations

Expand Down Expand Up @@ -924,6 +925,42 @@ const deepPartialUser = user.deepPartial();

> Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.


### `.required`

Contrary to the `.partial` method, the `.required` method makes all properties required.

Starting from this object:

```ts
const user = z.object({
email: z.string()
username: z.string(),
}).partial();
// { email?: string | undefined; username?: string | undefined }
```

We can create a required version:

```ts
const requiredUser = user.required();
// { email: string; username: string }
```

You can also specify which properties to make required:

```ts
const requiredEmail = user.required({
email: true,
});
/*
{
email: string;
username?: string | undefined;
}
*/
```

### `.passthrough`

By default Zod object schemas strip out unrecognized keys during parsing.
Expand Down
17 changes: 16 additions & 1 deletion deno/lib/__tests__/partials.test.ts
Expand Up @@ -147,7 +147,22 @@ test("required", () => {
expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault);
});

test("with mask", async () => {
test("required with mask", () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
country: z.string().optional(),
});

const requiredObject = object.required({ age: true });
expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString);
expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber);
expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault);
expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional);
});

test("partial with mask", async () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
Expand Down
41 changes: 33 additions & 8 deletions deno/lib/types.ts
Expand Up @@ -1915,16 +1915,41 @@ export class ZodObject<
{ [k in keyof T]: deoptional<T[k]> },
UnknownKeys,
Catchall
> {
>;
required<Mask extends { [k in keyof T]?: true }>(
mask: Mask
): ZodObject<
objectUtil.noNever<{
[k in keyof T]: k extends keyof Mask ? deoptional<T[k]> : T[k];
}>,
UnknownKeys,
Catchall
>;
required(mask?: any) {
const newShape: any = {};
for (const key in this.shape) {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = (newField as ZodOptional<any>)._def.innerType;
}
if (mask) {
util.objectKeys(this.shape).map((key) => {
if (util.objectKeys(mask).indexOf(key) === -1) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = (newField as ZodOptional<any>)._def.innerType;
}
newShape[key] = newField;
}
});
} else {
for (const key in this.shape) {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = (newField as ZodOptional<any>)._def.innerType;
}

newShape[key] = newField;
newShape[key] = newField;
}
}
return new ZodObject({
...this._def,
Expand Down
17 changes: 16 additions & 1 deletion src/__tests__/partials.test.ts
Expand Up @@ -146,7 +146,22 @@ test("required", () => {
expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault);
});

test("with mask", async () => {
test("required with mask", () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
field: z.string().optional().default("asdf"),
country: z.string().optional(),
});

const requiredObject = object.required({ age: true });
expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString);
expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber);
expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault);
expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional);
});

test("partial with mask", async () => {
const object = z.object({
name: z.string(),
age: z.number().optional(),
Expand Down
41 changes: 33 additions & 8 deletions src/types.ts
Expand Up @@ -1915,16 +1915,41 @@ export class ZodObject<
{ [k in keyof T]: deoptional<T[k]> },
UnknownKeys,
Catchall
> {
>;
required<Mask extends { [k in keyof T]?: true }>(
mask: Mask
): ZodObject<
objectUtil.noNever<{
[k in keyof T]: k extends keyof Mask ? deoptional<T[k]> : T[k];
}>,
UnknownKeys,
Catchall
>;
required(mask?: any) {
const newShape: any = {};
for (const key in this.shape) {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = (newField as ZodOptional<any>)._def.innerType;
}
if (mask) {
util.objectKeys(this.shape).map((key) => {
if (util.objectKeys(mask).indexOf(key) === -1) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = (newField as ZodOptional<any>)._def.innerType;
}
newShape[key] = newField;
}
});
} else {
for (const key in this.shape) {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = (newField as ZodOptional<any>)._def.innerType;
}

newShape[key] = newField;
newShape[key] = newField;
}
}
return new ZodObject({
...this._def,
Expand Down