TypeScript Course
TypeScript
/
Advanced

DTO (Data Transfer Object) Patterns

Definition

An architectural pattern used to define objects that transport data between processes (e.g., between a Backend and Frontend). They decouple the internal database models from the external API shapes.

Explain Like I'm New

A Database Model is the raw ingredients in the kitchen. The DTO is the beautiful plated meal served to the customer. You don't want to serve raw ingredients (like sending the user's password hash or database internal IDs to the frontend). The DTO is a strictly typed interface defining exactly what the frontend is allowed to see.

Real World Example

A Backend User entity has 20 fields. You create a `CreateUserDTO` interface for the Registration form (only needs email/password), and a `UserResponseDTO` for the frontend (strips the password).

Common Use Cases

  • •NestJS architecture
  • •Full-stack TypeScript apps
  • •Securing API boundaries

Interactive Example

// Backend Database Model
interface UserEntity {
  id: string;
  email: string;
  passwordHash: string;
  lastLoginIp: string;
  createdAt: Date;
}

// DTO for the Frontend (Data traveling over the network)
// We use Omit to perfectly strip sensitive data while keeping types in sync
export type UserResponseDTO = Omit<UserEntity, "passwordHash" | "lastLoginIp">;

// DTO for what the Frontend sends to the Backend during signup
export type CreateUserRequestDTO = Pick<UserEntity, "email"> & {
  passwordRaw: string; // The frontend sends a raw password, not a hash
};

// Frontend API Call using the DTO contract
async function signup(payload: CreateUserRequestDTO): Promise<UserResponseDTO> {
  // fetch...
}

Interview Questions

basic

  • What does DTO stand for?

intermediate

  • Why use a DTO instead of just returning the Database Model directly?

advanced

  • How do DTOs relate to Utility Types like `Omit` and `Pick`?

Flash Cards

Question

Why use DTOs instead of DB models?

Click to reveal answer
Answer

Security and Decoupling. If you return the DB model directly, you might accidentally expose sensitive fields (passwords, salts). Furthermore, if you change your database schema, you don't want every frontend application relying on that API to suddenly break. The DTO acts as a stable contract.

Question

How do they relate to Utility types?

Click to reveal answer
Answer

In full-stack TS, developers rarely write DTOs from scratch. They import the base Database Entity, and use Utilities to build the DTO: `export type UserPublicDTO = Omit<DbUser, 'password' | 'ssn'>;`.