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

Support for zod.input to allow properties with defaults #24

Open
bhvngt opened this issue Jun 20, 2024 · 0 comments
Open

Support for zod.input to allow properties with defaults #24

bhvngt opened this issue Jun 20, 2024 · 0 comments

Comments

@bhvngt
Copy link

bhvngt commented Jun 20, 2024

Thanks for creating this great library. Save me a ton of work in my current project.

I have many Zod schemas having properties with default values. z.infer gives z.output inference by default. However, when sending data to the constructor, I find it convenient to use z.input which marks the properties with default value as optional - ref

To illustrate

const UserProfileSchema = z.object({
  name: z.string(),
  age: z.number(),
  role: z.string().default("Admin"),
});
class UserProfile extends Z.class(UserProfileSchema.shape) {
  // constructor(input: z.input<typeof UserProfileSchema>) {
  // super(input as z.output<typeof UserProfileSchema>);
  // }
  getMessage() {
    return `Hello ${this.name}, you are ${String(
      this.age
    )} years old and your role is ${this.role}`;
  }
}

const profile = new UserProfile({ name: "John", age: 30 }); // gives TS error unless constructor code is uncommented
profile.getMessage();

Here's the playground.

Is there a way to send z.input based schema inference for the constructor parameters without resorting to overloading the constructor? While overloading a constructor is not a big deal, it just becomes repeatative for all my Zod classes.

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

No branches or pull requests

1 participant