colinhacks/zod

Rename property of another Zod object with Transform method

Opened this issue · 0 comments

Possible problem:

When I have some defined schema and I want to change only the property value from it to be validated on PARSE, it not work as expected.

Inside application, the type infers correctly, like my object.ids, can access the possible object with the new property name, but on PARSE, seems to not recognize the renamed property it expects to the last one, e.g., disabled_group.

I have another schema with the same shape, just need to change the property name validation, so I tried with transform, maybe I missunderstood the usage of it.

Make a new schema with ids name, works fine! So I'm following this way at the time

e.g.:

// zod helper
import { ZodEffects, ZodType } from 'zod';

export namespace ZodHelpers {
  export function nonemptyObjects<T extends ZodType>(zodBaseObject: T): ZodEffects<T> {
    return zodBaseObject.refine((schema) => Object.keys(schema).length > 0, 'JSON cannot be empty');
  }
}

// some dto schema
export const BulkDisableQuerySchema = ZodHelpers.nonemptyObjects(
    z
      .object({
        disabled_group: z.array(z.number()).nonempty().optional(),
      })
      .strict(),
);

// ❌ NOT WORK -> keep expecting for disable_group
// transformed schema with new property name, but shape and everything same
export const BulkDeleteQuerySchema = BulkDisableQuerySchema.transform((property) => ({
  ids: property.disabled_group
})

// ✅ WORK as expected, but it's the same shape
export const BulkDisableQuerySchema = ZodHelpers.nonemptyObjects(
    z
      .object({
        ids: z.array(z.number()).nonempty().optional(),
      })
      .strict(),
);

Error

{
    "issues": [
        {
            "code": "unrecognized_keys",
            "keys": [
                "ids"
            ],
            "path": [],
            "message": "Unrecognized key(s) in object: 'ids'"
        },
        {
            "code": "custom",
            "message": "JSON cannot be empty",
            "path": []
        }
    ],
    "name": "ZodError"
}

Expected

  • Working: type inside project already able to access using ids.
  • Not working: On parse, it's not identifying the NEW property name.

Version:

  • Nestjs: ^10.0.0
  • Zod: ^3.23.8