Skip to main content

Lesson 7 of 7

Practice & Quiz - DTOs, Validation & Patterns

Reinforce production TypeScript patterns - DTOs, Zod validation, typed error hierarchies, the Builder pattern, and the Result type - with a focused exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical: Zod Schema → DTO → Mapper Pipeline

Practical: Zod Schema → DTO → Mapper Pipeline
// The complete pipeline: Zod schema → TypeScript type → DTO mapper
import { z } from "zod";

// ── 1. Single source of truth: Zod schema ────────────────────
const CreateProjectSchema = z.object({
  name:        z.string().min(1, "Name required").max(100),
  description: z.string().max(1000).optional(),
  deadline:    z.string().datetime().transform(v => new Date(v)).optional(),
  visibility:  z.enum(["public", "private"]).default("private"),
});

// ── 2. Derive the TypeScript type from the schema ─────────────
type CreateProjectDTO = z.infer<typeof CreateProjectSchema>;
// { name: string; description?: string; deadline?: Date; visibility: "public" | "private" }

// ── 3. Domain type (internal) ─────────────────────────────────
interface Project {
  readonly id:  number;
  name:         string;
  description:  string | null;
  deadline:     Date | null;
  visibility:   "public" | "private";
  ownerId:      number;          // internal - never exposed in response
  readonly createdAt: Date;
  updatedAt:    Date;
}

// ── 4. Response DTO (what the API returns) ────────────────────
interface ProjectResponseDTO {
  id:          number;
  name:        string;
  description: string | null;
  deadline:    string | null;  // ISO string - not Date
  visibility:  "public" | "private";
  createdAt:   string;
  updatedAt:   string;
  // ownerId omitted - internal field
}

// ── 5. Mapper: domain → response DTO ────────────────────────
function toProjectDTO(p: Project): ProjectResponseDTO {
  const { ownerId: _, ...rest } = p;  // strip internal field
  return {
    ...rest,
    deadline:  p.deadline?.toISOString() ?? null,
    createdAt: p.createdAt.toISOString(),
    updatedAt: p.updatedAt.toISOString(),
  };
}

// ── 6. Validate input with safeParse ─────────────────────────
const raw = { name: "My Project", visibility: "public" };
const parsed = CreateProjectSchema.safeParse(raw);

if (parsed.success) {
  const dto: CreateProjectDTO = parsed.data; // fully typed ✅
  console.log(dto.visibility); // "public"
} else {
  console.error(parsed.error.flatten().fieldErrors);
}

Module Quiz

Module Quiz
Question 1 of 5

Why should response DTOs represent dates as `string` instead of `Date`?

Tip

Tip

Practice Practice Quiz DTOs Validation Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

TypeScript = JavaScript + static types → fewer bugs, better tooling

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz DTOs Validation Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz DTOs Validation Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done