Skip to content

Instantly share code, notes, and snippets.

@dimfeld
Last active December 13, 2024 22:32
Show Gist options
  • Save dimfeld/02cd41dad63c095291c15619484ab170 to your computer and use it in GitHub Desktop.
Save dimfeld/02cd41dad63c095291c15619484ab170 to your computer and use it in GitHub Desktop.
Zod DeepRequired
import { describe, expect, it } from 'vitest';
import { z } from 'zod';
import { deepRequired } from './zod_util.js';
describe('deepRequired', () => {
it('makes all fields in a flat object required', () => {
const schema = z.object({
required: z.string(),
optional: z.string().optional(),
nullable: z.string().nullable(),
optionalAndNullable: z.string().optional().nullable(),
});
const required = deepRequired(schema);
// All fields should be required and non-nullable
type Schema = z.infer<typeof required>;
const shouldBeRequired: Schema = {
required: 'test',
optional: 'test',
nullable: 'test',
optionalAndNullable: 'test',
};
// @ts-expect-error - missing properties should error
const shouldError: Schema = {
required: 'test',
};
// Test runtime validation
expect(() =>
required.parse({
required: 'test',
optional: 'test',
nullable: 'test',
optionalAndNullable: 'test',
})
).not.toThrow();
// Should throw when missing properties
expect(() =>
required.parse({
required: 'test',
})
).toThrow();
});
it('makes nested object fields required', () => {
const schema = z.object({
nested: z
.object({
required: z.string(),
optional: z.string().optional(),
})
.optional(),
});
const required = deepRequired(schema);
// All fields should be required and non-nullable
type Schema = z.infer<typeof required>;
const shouldBeRequired: Schema = {
nested: {
required: 'test',
optional: 'test',
},
};
const shouldError: Schema = {
// @ts-expect-error - missing properties should error
nested: {
required: 'test',
},
};
// Test runtime validation
expect(() =>
required.parse({
nested: {
required: 'test',
optional: 'test',
},
})
).not.toThrow();
// Should throw when missing properties
expect(() =>
required.parse({
nested: {
required: 'test',
},
})
).toThrow();
});
it('makes array elements required', () => {
const schema = z.object({
array: z.array(
z.object({
required: z.string(),
optional: z.string().optional(),
})
),
});
const required = deepRequired(schema);
// Test runtime validation
expect(() =>
required.parse({
array: [
{
required: 'test',
optional: 'test',
},
],
})
).not.toThrow();
// Should throw when missing properties in array elements
expect(() =>
required.parse({
array: [
{
required: 'test',
},
],
})
).toThrow();
});
it('makes tuple elements required', () => {
const schema = z.object({
tuple: z.tuple([z.string(), z.number().optional(), z.boolean().nullable()]),
});
const required = deepRequired(schema);
// Test runtime validation
expect(() =>
required.parse({
tuple: ['test', 42, true],
})
).not.toThrow();
// Should throw when missing tuple elements
expect(() =>
required.parse({
tuple: ['test'],
})
).toThrow();
});
it('preserves non-optional/nullable schemas', () => {
const schema = z.object({
string: z.string(),
number: z.number(),
boolean: z.boolean(),
literal: z.literal('test'),
enum: z.enum(['a', 'b', 'c']),
});
const required = deepRequired(schema);
// Test that the schemas are unchanged
expect(() =>
required.parse({
string: 'test',
number: 42,
boolean: true,
literal: 'test',
enum: 'a',
})
).not.toThrow();
// Should still throw for invalid values
expect(() =>
required.parse({
string: 42,
number: 'test',
boolean: 'true',
literal: 'wrong',
enum: 'd',
})
).toThrow();
});
});
import {
ZodTypeAny,
ZodObject,
ZodOptional,
ZodArray,
ZodNullable,
ZodTuple,
ZodRawShape,
ZodTupleItems,
} from 'zod';
export type DeepRequired<T extends ZodTypeAny> =
T extends ZodObject<ZodRawShape>
? ZodObject<
{ [k in keyof T['shape']]: DeepRequired<T['shape'][k]> },
T['_def']['unknownKeys'],
T['_def']['catchall']
>
: T extends ZodArray<infer Type, infer Card>
? ZodArray<DeepRequired<Type>, Card>
: T extends ZodOptional<infer Type>
? DeepRequired<Type>
: T extends ZodNullable<infer Type>
? DeepRequired<Type>
: T extends ZodTuple<infer Items>
? {
[k in keyof Items]: Items[k] extends ZodTypeAny ? DeepRequired<Items[k]> : never;
} extends infer PI
? PI extends ZodTupleItems
? ZodTuple<PI>
: never
: never
: T;
function deepRequiredInternal(schema: ZodTypeAny): any {
if (schema instanceof ZodObject) {
const newShape: any = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = deepRequiredInternal(fieldSchema);
}
return new ZodObject({
...schema._def,
shape: () => newShape,
}) as any;
} else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepRequiredInternal(schema.element),
});
} else if (schema instanceof ZodOptional) {
return deepRequiredInternal(schema.unwrap());
} else if (schema instanceof ZodNullable) {
return deepRequiredInternal(schema.unwrap());
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item: any) => deepRequiredInternal(item)));
} else {
return schema;
}
}
export function deepRequired<T extends ZodTypeAny>(schema: T): DeepRequired<T> {
return deepRequiredInternal(schema) as DeepRequired<T>;
}
These files are licensed under the MIT license, as with the Zod project.
Copyright 2024 Daniel Imfeld, Colin McDonnell
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment