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

Problem with parse method when zod.transform is used in a schema #31

Open
piotar opened this issue Dec 10, 2024 · 0 comments
Open

Problem with parse method when zod.transform is used in a schema #31

piotar opened this issue Dec 10, 2024 · 0 comments

Comments

@piotar
Copy link

piotar commented Dec 10, 2024

The problem occurs when transform has been used in the schema.

I don't know what the intention was, but when parsing the schema, zod class performs double parsing. In the parse function(https://github.com/sam-goodwin/zod-class/blob/main/src/index.ts#L305) and in the constructor(https://github.com/sam-goodwin/zod-class/blob/main/src/index.ts#L187).

I think this is also an performance issue, because why would we parse the schema twice?

There is also a problem of types in constructor when we use transform from zod.

Example code to reproduce problem:

https://stackblitz.com/edit/stackblitz-starters-cg4bsqz2?file=main.ts&view=editor

import { z } from 'zod';
import { Z } from 'zod-class';

enum Color {
  Red,
  Blue,
  Green,
}

enum ColorAsString {
  Red = 'red',
  Blue = 'blue',
  Green = 'green',
}

const ColorMap = {
  [ColorAsString.Red]: Color.Red,
  [ColorAsString.Blue]: Color.Blue,
  [ColorAsString.Green]: Color.Green,
} satisfies Record<ColorAsString, Color>;

class CustomSchema extends Z.class({
  color: z.nativeEnum(ColorAsString).transform((c) => ColorMap[c]),
}) {}

// Works fine, but types are incorrect
console.log(new CustomSchema({ color: ColorAsString.Blue }));

// Throws an exception because it parses twice
console.log(CustomSchema.parse({ color: ColorAsString.Blue }));
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