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

feat(enum): return enum from object keys #1216

Merged
merged 7 commits into from
Jul 18, 2022
Merged

Conversation

ecyrbe
Copy link
Contributor

@ecyrbe ecyrbe commented Jun 20, 2022

This should close this issue: #1085

usage

const result: Z.ZodEnum< [ 'a', 'b' ] > = z.object({ a: z.string(), b: z.string().optional() }).enum();

it allows to extract the keys of a zob object schema as a zod enum.

Tell me if it's ok.

@netlify
Copy link

netlify bot commented Jun 20, 2022

Deploy Preview for guileless-rolypoly-866f8a ready!

Name Link
🔨 Latest commit 4bdcd01
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/62d4fe9b395be800087346c0
😎 Deploy Preview https://deploy-preview-1216--guileless-rolypoly-866f8a.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

@colinhacks
Copy link
Owner

colinhacks commented Jul 18, 2022

That conversion from a union to a tuple is some black magic. Love it.

I renamed this method to keyof to stay in closer agreement with TypeScript terminology.

Great PR. 🙌

@colinhacks colinhacks merged commit 1d16205 into colinhacks:master Jul 18, 2022
@ecyrbe
Copy link
Contributor Author

ecyrbe commented Jul 18, 2022

@colinhacks yeah, i became a typescript vodoo master recently. Don't ask me what it cost me 🤣

@betafcc
Copy link

betafcc commented Aug 10, 2022

Really cool trick @ecyrbe, discovered half of it to make tuple permutations but didn't occur to me to use the function overload trick to get ordering, nice.

Do beware of how TS treats key order differently than JS engines though:

z.object({ a: z.string(), '1': z.string() }).keyof()._def.values
// TS says it's ['a', '1']
// JS runtime it's ['1', 'a']

Seems to not be an issue for internal use with zod enum, but thought pointing this out can be of some value since the test cases only have non numeral strings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants