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: Improve Object Type Handling in Zod Conversion #293

Merged
merged 1 commit into from
Nov 29, 2024

Conversation

Yoon-Hae-Min
Copy link
Contributor

Why

  • When defining an object type within an object, it is inferred as any when converted to Zod.
    image

  • any is a supertype of object, necessitating a stronger assertion of the type.

  • After generating the type, during validation, any includes optional, which leads to a mismatch with the original type.
    image

  • This issue is resolved by treating the object as record any. => z.record(z.any())

Result

case 1: primitive object

export type Obj = object;
// Generated by ts-to-zod
import { z } from "zod";

export const objSchema = z.record(z.any());

case 2: object in object

export interface ExampleObject {
  result: object;
}
// Generated by ts-to-zod
import { z } from "zod";

export const exampleObjectSchema = z.object({
  result: z.record(z.any()),
});

Test

I added a test case related to this PR.

image

Copy link
Collaborator

@tvillaren tvillaren left a comment

Choose a reason for hiding this comment

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

Thanks for your addition!

@tvillaren tvillaren merged commit 090d050 into fabien0102:main Nov 29, 2024
2 checks passed
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.

2 participants