Skip to content

Add an API to invert codecs #5374

@Nicolapps

Description

@Nicolapps

If I already have a codec, for instance:

const isoDatetimeToDate = z.codec(
  z.iso.datetime(),
  z.date(),
  {
    decode: (isoString) => new Date(isoString),
    encode: (date) => date.toISOString(),
  }
);

It might be helpful for me to get the inverse codec. Of course, I can write it manually, but it can be tedious:

const isoDatetimeToDate = z.codec(
  z.iso.datetime(),
  z.date(),
  {
    decode: (isoString) => new Date(isoString),
    encode: (date) => date.toISOString(),
  }
);

const dateToIsoDatetime = z.codec(
  z.date(),
  z.iso.datetime(),
  {
    decode: (date) => date.toISOString(),
    encode: (isoString) => new Date(isoString),
  }
);

Ideally, there would be a built-in API to z.ZodCodec that automatically generates the inverse codec:

const isoDatetimeToDate = z.codec(
  z.iso.datetime(),
  z.date(),
  {
    decode: (isoString) => new Date(isoString),
    encode: (date) => date.toISOString(),
  }
);

const dateToIsoDatetime = isoDatetimeToDate.invert();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions