zod
zod copied to clipboard
feat(#1582): Allow for passing enums or ZodNativeEnums to ZodObject and fix ZodRecord
Closes #1582
This PR makes it possible to pass an enum
or an instance of a ZodNativeEnum
to a ZodObject
as its shape. Output/Input types are inferred correctly, and conversion logic to real ZodRawShape
is working as expected.
Additionally, this PR also fixes ZodRecord
. When passed an instance of ZodNativeEnum
to its keySchema
, it no longer wraps the inferred type inside a Partial
.
Important note
This is an initial solution. There are many others, like add a required()
method to z.record()
to get rid of the Partial
, or add a .mapValues()
method to ZodNativeEnum
to allow for mapping the enum values against a zod schema, among others.
Please feel free to provide any feedback.
Example from issue
import { z } from "./src";
enum Status {
NotStarted = "not-started",
InProgress = "in-progress",
CompletedSuccesfully = "completed-succesfully",
CompletedWithFailures = "completed-with-failures",
Failed = "failed",
}
/**
* Let's call this mapping `Step 1`
*/
type StatusReports = {
[k in Status]: number;
};
/**
* And this intersection, `Step 2`
*/
type StatusReport = StatusReports & {
total: number;
};
const sr: StatusReport = {
total: 5,
[Status.NotStarted]: 1,
[Status.InProgress]: 1,
[Status.CompletedSuccesfully]: 1,
[Status.CompletedWithFailures]: 1,
[Status.Failed]: 1,
};
/**
* Step 1
*/
const StatusReports = z.record(z.nativeEnum(Status), z.number());
type StatusReports_ = z.infer<typeof StatusReports>;
// ^?

/**
* Step 2
*/
const StatusReport = z.object(Status).extend({ total: z.number() });
type StatusReport_ = z.infer<typeof StatusReport>;
// ^?

Deploy Preview for guileless-rolypoly-866f8a ready!
Built without sensitive environment variables
Name | Link |
---|---|
Latest commit | 5ae545ef33c701a30135ce35f7d01e8681733360 |
Latest deploy log | https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/639420e064e51e000850004b |
Deploy Preview | https://deploy-preview-1660--guileless-rolypoly-866f8a.netlify.app |
Preview on mobile | Toggle QR Code...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify site settings.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.