0Pricing
tRPC End-to-End Type Safe APIs · Lección

Transformación y refinamiento de datos con Zod

Vaya más allá de la validación básica transformando los valores analizados y añadiendo reglas de refinamiento personalizadas con Zod.

Transformación y refinamiento de datos con Zod es una lección gratuita de tRPC End-to-End Type Safe APIs en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de tRPC End-to-End Type Safe APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Beyond Pass/Fail

Zod does more than accept or reject data. It can transform valid input into a cleaner shape and apply custom rules that built-in validators cannot express.

The transform Method

.transform() changes a value after it passes validation, producing a new output type.

const trimmed = z.string().transform((s) => s.trim());
trimmed.parse("  hi  "); // "hi"

Coercing Types

Zod can coerce inputs, useful for query strings that arrive as text but should be numbers.

const page = z.coerce.number().int().positive();
page.parse("5"); // 5 as a number

Default Values

Provide a fallback when a field is missing.

const schema = z.object({
  limit: z.number().default(20),
});
schema.parse({}); // { limit: 20 }

Custom Refinements

.refine() adds a custom boolean check with a message when it fails.

const password = z.string().refine(
  (val) => val.length >= 8,
  { message: "Too short" }
);

Cross-Field Validation

Refine an object to compare two fields, like confirming a password.

const form = z.object({
  pw: z.string(),
  confirm: z.string(),
}).refine((d) => d.pw === d.confirm, {
  message: "Passwords must match",
  path: ["confirm"],
});

superRefine for Multiple Errors

.superRefine() lets you push several issues in one pass for richer validation.

const s = z.string().superRefine((val, ctx) => {
  if (!/[A-Z]/.test(val)) ctx.addIssue({ code: "custom", message: "Need uppercase" });
  if (!/[0-9]/.test(val)) ctx.addIssue({ code: "custom", message: "Need digit" });
});

Chaining Transforms

Validation and transformation chain in order.

const slug = z.string()
  .min(1)
  .transform((s) => s.toLowerCase().replace(/\s+/g, "-"));
slug.parse("Hello World"); // "hello-world"

Input vs Output Types

After a transform, the input type and output type differ. Use z.input and z.output to read each.

type In = z.input<typeof page>;   // string | number
type Out = z.output<typeof page>; // number

Safe Parsing

Use safeParse to get a result object instead of throwing, ideal for handling errors gracefully.

const r = password.safeParse("short");
if (!r.success) console.log(r.error.issues);

Pipe for Validate-then-Transform

Use .pipe() to first coerce or transform a value and then run further validation on the result.

const id = z.string().transform(Number).pipe(z.number().int());

Quick Check

Test your Zod knowledge.

Recap

You leveled up your Zod schemas:

  • transform and coerce reshape valid data
  • refine / superRefine add custom and cross-field rules
  • safeParse handles errors without throwing

These tools turn Zod into a powerful data shaping and validation layer.

Preguntas frecuentes

¿La lección «Transformación y refinamiento de datos con Zod» es gratis?

Sí — el texto completo de «Transformación y refinamiento de datos con Zod» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de tRPC End-to-End Type Safe APIs, actualiza a CoddyKit PRO. El curso de tRPC End-to-End Type Safe APIs incluye 4 lecciones en total.

¿Qué aprenderé en «Transformación y refinamiento de datos con Zod»?

Vaya más allá de la validación básica transformando los valores analizados y añadiendo reglas de refinamiento personalizadas con Zod. Practicas tRPC End-to-End Type Safe APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar tRPC End-to-End Type Safe APIs?

No se requiere experiencia previa. tRPC End-to-End Type Safe APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Transformación y refinamiento de datos con Zod»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de tRPC End-to-End Type Safe APIs?

Sí. Cada lección de tRPC End-to-End Type Safe APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción a los esquemas de Zod
  2. Definición de esquemas complejos de Zod
  3. Integración de Zod en procedimientos de tRPC
  4. Transformación y refinamiento de datos con Zod
← Volver a tRPC End-to-End Type Safe APIs