Course contentsShow
← TypeScript
Lesson 933 of 1,79621. The unknown TypeFree lesson

Mapping API Responses to Domain Types

Transform validated unknown data into strongly-typed domain models with constructor functions.

Mapping API Responses to Domain Types

What you'll learn: How to transform validated unknown data from APIs into clean, strongly-typed domain models using constructor functions.

Why We Need Mapping

You've validated your API response is the shape you expect — but it's still just raw data. Your application shouldn't work with primitive objects everywhere. Instead, you want domain types: classes or objects with methods, computed properties, and business logic encapsulated.

Think of it like receiving raw ingredients (validated API data) and cooking them into a proper meal (your domain model). The validation ensured the ingredients are safe; mapping turns them into something useful.

The Pattern: Constructor Functions

After narrowing unknown data with type guards, pass it to a constructor function that creates your domain object:

interface UserData {
  id: number;
  name: string;
  email: string;
  created_at: string; // ISO date string
}

class User {
  constructor(
    public id: number,
    public name: string,
    public email: string,
    public createdAt: Date
  ) {}

  getDisplayName(): string {
    return `${this.name} (${this.email})`;
  }
}

function createUser(data: UserData): User {
  return new User(
    data.id,
    data.name,
    data.email,
    new Date(data.created_at) // Transform string to Date
  );
}

// After validation:
function parseApiResponse(response: unknown): User {
  if (!isUserData(response)) {
    throw new Error("Invalid user data");
  }
  return createUser(response); // Strongly typed!
}

Notice how createUser handles the transformation: snake_case becomes camelCase, strings become Dates, and you get a real User instance with methods.

Key Takeaway: After validating unknown API data, use constructor functions to map raw data into domain types with proper structure, naming conventions, and behavior — giving you type-safe objects throughout your application.