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 .extend to Zod enums #3999

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jeremy-code
Copy link

@jeremy-code jeremy-code commented Feb 20, 2025

  • Add .extend method to Enum class in Zod to allow extending enums with additional values

Essentially, adds functionality equivalent to the following.

const SalmonAndTrout = z.enum(["Salmon", "Trout"]);
const FishEnum = z.enum([...SalmonAndTrout.options, "Tuna"]);

const SalmonAndTrout = z.enum(["Salmon", "Trout"]);
const FishEnum = SalmonAndTrout.extend(["Tuna"]);

I think it would be useful to have alongside .extract and .exclude. The behavior is also equivalent to z.object's .extend. I couldn't find any issues on this or similar, hence the PR. Let me know what you think.

Summary by CodeRabbit

  • New Features

    • Introduced a method to extend existing enum definitions with additional values, enhancing flexibility in creating comprehensive enum types.
  • Tests

    • Added test cases to ensure the new enum extension functionality operates correctly.

Copy link

coderabbitai bot commented Feb 20, 2025

Walkthrough

This update introduces a new .extend() method to the Zod enum functionality, allowing the creation of extended enums that inherit existing values while appending new ones. Documentation has been updated with an example, a corresponding test case has been added to verify the behavior, and the underlying type definitions have been modified to support this extension mechanism.

Changes

File(s) Summary
README.md, src/types.ts Documented and implemented the new .extend() method for creating supersets of enums in Zod.
src/types.ts Updated method signatures for extract, exclude, and create to accept additional parameters.
src/tests/enum.test.ts Added a new test case for the .extend() method to verify the functionality of extended enums.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant Z as ZodEnum
    participant N as ExtendedEnum

    U->>Z: Call .extend(newValues)
    Z->>Z: Merge existing values with newValues
    Z-->>U: Return new ExtendedEnum with combined values
Loading

Poem

I'm a bunny with a coding rush,
Hopping through enums without a fuss.
I add new values with a joyful leap,
Extending Zod's garden for code to keep.
Carrots and enums, a feast so neat!
🐇🌟 Hop along to the beat!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Feb 20, 2025

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 3dd4a28
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/67b6a79c5509020008ad8282
😎 Deploy Preview https://deploy-preview-3999--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 configuration.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/__tests__/enum.test.ts (1)

44-53: LGTM! Consider adding more test cases for comprehensive coverage.

The test correctly verifies the type inference for the extended enum. However, to ensure robust functionality, consider adding the following test cases:

test("extends - edge cases", () => {
  const BaseEnum = z.enum(["A", "B"]);
  
  // Test extending with empty array
  const EmptyExtended = BaseEnum.extends([]);
  util.assertEqual<z.infer<typeof EmptyExtended>, "A" | "B">(true);
  
  // Test extending with duplicate values
  const DuplicateExtended = BaseEnum.extends(["B", "C"]);
  util.assertEqual<z.infer<typeof DuplicateExtended>, "A" | "B" | "C">(true);
  
  // Test runtime behavior
  expect(DuplicateExtended.options).toEqual(["A", "B", "C"]);
  expect(() => DuplicateExtended.parse("D")).toThrow();
  
  // Test error mapping
  const ErrorMappedEnum = BaseEnum.extends(["C"], {
    errorMap: () => ({ message: "Invalid value!" })
  });
  const result = ErrorMappedEnum.safeParse("D");
  expect(result.success).toBe(false);
  if (!result.success) {
    expect(result.error.issues[0].message).toBe("Invalid value!");
  }
});
src/types.ts (1)

4410-4418: Add JSDoc documentation for the new extends method.

The implementation looks good but is missing documentation to explain its purpose and parameters.

Add JSDoc comments like this:

+  /**
+   * Creates a new enum by extending the current enum with additional values.
+   * @param values - Array of new values to add to the enum
+   * @param newDef - Optional parameters to customize the new enum definition
+   * @returns A new ZodEnum instance containing all values
+   */
  extends<const ToExtend extends readonly [string, ...string[]]>(
    values: ToExtend,
    newDef: RawCreateParams = this._def
  ): ZodEnum<[...T, ...Writeable<ToExtend>]> {
README.md (1)

1170-1170: Markdown Styling: Emphasis Markers

There are extra spaces inside the emphasis markers on the .extends() header. For a cleaner markdown style (per MD037), consider changing
** .extends() **
to
**.extends()**.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)


1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e308703 and 65e0427.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • src/__tests__/enum.test.ts (1 hunks)
  • src/types.ts (1 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)


1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)

🔇 Additional comments (2)
src/types.ts (1)

4410-4418: LGTM! The implementation is clean and type-safe.

The implementation correctly extends the enum by:

  • Using proper type constraints
  • Efficiently combining arrays
  • Preserving the original definition
  • Allowing customization via optional params
README.md (1)

1170-1178: Documentation Addition: Introducing the .extends() Method

The new documentation clearly explains how to extend an existing enum with additional values. The example:

const SalmonAndTrout = z.enum(["Salmon", "Trout"]);
const FishEnum = SalmonAndTrout.extends(["Tuna"]);

illustrates how users can create a superset enum. Please double-check that this example aligns precisely with the implementation in the type definitions (e.g., in src/types.ts) for consistency.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)


1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)

- Add `.extend` method to Enum class in Zod to allow extending enums with additional values
@jeremy-code jeremy-code changed the title Add .extends to Zod enums Add .extend to Zod enums Feb 20, 2025
@jeremy-code
Copy link
Author

Sorry! Just renamed .extends to .extend. I think I mixed up the JS/TS keyword in my head and thought the .object method was .extends but it is actually .extend, which aligns with .extract and .exclude better.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/types.ts (1)

4410-4418: Add documentation for the new .extend() method.

The implementation looks good but would benefit from JSDoc documentation explaining the purpose, parameters and return value.

Add documentation above the method:

+  /**
+   * Creates a new enum by extending an existing enum with additional values
+   * @param values - Array of new values to add to the enum
+   * @param newDef - Optional parameters to override in the new enum
+   * @returns A new ZodEnum instance containing all values
+   */
   extend<const ToExtend extends readonly [string, ...string[]]>(
     values: ToExtend,
     newDef: RawCreateParams = this._def
   ): ZodEnum<[...T, ...Writeable<ToExtend>]> {
README.md (2)

1170-1171: Formatting Issue: Remove extra spaces in emphasis markers
There are extra spaces inside the emphasis markers in the new heading. To comply with markdown lint MD037 (no-space-in-emphasis), consider changing:

-** `.extend()` **
+**`.extend()`**
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)


1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)


1176-1177: Documentation Continuity
The transition from the .extend() example to the subsequent section on .exclude/.extract() is smooth. For clarity, consider adding a brief note that explains when one might use .extend() versus .exclude/.extract so that users can quickly decide the appropriate method for their use case.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 65e0427 and 3dd4a28.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • src/__tests__/enum.test.ts (1 hunks)
  • src/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/tests/enum.test.ts
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)


1170-1170: Spaces inside emphasis markers
null

(MD037, no-space-in-emphasis)

🔇 Additional comments (2)
src/types.ts (1)

4410-4418: LGTM! Implementation follows best practices.

The implementation:

  • Maintains immutability by creating a new instance
  • Uses const generics for type safety
  • Preserves original definition parameters
  • Correctly merges the enum values
README.md (1)

1171-1175: New Enum Extension Example
The new example clearly demonstrates how to extend an existing Zod enum using the newly introduced .extend() method. The code snippet—creating a SalmonAndTrout enum and then extending it with "Tuna"—is self-explanatory and aligns with the intended functionality described in the PR objectives.

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.

1 participant