TypeScript 4-Layer Type Architecture in 2026: Domain, DTO, API, and UI Types That Never Bleed Into Each Other
A four-layer type architecture separates domain logic from transport contracts, API versions, and UI concerns. This prevents cascading changes and enforces clear boundaries between business rules and infrastructure.
A type system without boundaries becomes a liability when API contracts leak into domain models, DTOs dictate UI component shapes, and a single backend field rename cascades through the entire application. The four-layer type architecture establishes strict separation between domain types (business logic), DTO types (transport contracts), API types (versioned external contracts), and UI types (view models). Each layer owns its types and maps explicitly at boundaries, preventing implementation details from crossing architectural lines.
Most TypeScript applications fail by reusing backend DTOs everywhere. Developers import the same UserDTO type into domain services, API route handlers, and React components. When the API adds a nullable field or renames userId to user_id, the change propagates through all three layers. The blast radius of a single backend decision becomes the entire codebase. This coupling eliminates the ability to evolve any layer independently and creates a maintenance burden that scales with application size.
%% alt: Problem diagram showing cascading changes from backend DTO reuse
flowchart LR
A("Backend adds nullable field") --> B("DTO type changes")
B --> C("Domain logic breaks")
B --> D("API contracts fail")
B --> E("UI components crash")
style E stroke:#ef4444,fill:#450a0a,color:#fca5a5
The four-layer architecture solves this by establishing type ownership at each boundary. Domain types define business rules independent of transport format. DTOs define wire contracts that never leak beyond the API boundary. API types version external contracts separately from internal implementation. UI types mirror component requirements without knowledge of backend structure. Mapping functions at each boundary translate between these representations.
%% alt: Solution diagram showing isolated layer changes
flowchart LR
A("Backend adds nullable field") --> B("DTO type changes")
B --> C("Mapper absorbs change")
C --> D("Domain types unchanged")
C --> E("UI types unchanged")
style E stroke:#34d399,fill:#0b3b2e,color:#d1fae5
Key Takeaways
- Reusing DTOs across layers creates cascading changes when backend contracts evolve.
- Domain types define business rules independent of transport format or database schema.
- Explicit mapping at boundaries prevents implementation details from leaking between layers.
- UI types should mirror component requirements, not backend structure.
- Versioned API types allow breaking changes without rewriting the entire application.
The Anti-Pattern: Reusing DTOs Everywhere
The most common failure pattern in TypeScript applications appears when developers treat backend response shapes as universal types. A UserDTO from the API becomes the domain model, the component prop type, and the validation schema. This approach eliminates mapping code but creates tight coupling between infrastructure and business logic.
// Anti-pattern: single type for all contexts
interface UserDTO {
id: string;
email: string;
created_at: string; // ISO string from backend
metadata?: Record<string, unknown>;
}
// Domain service uses DTO directly
class UserService {
async findUser(id: string): Promise<UserDTO> {
return fetch(`/api/users/${id}`).then(r => r.json());
}
}
// Component uses DTO directly
function UserProfile({ user }: { user: UserDTO }) {
// Business logic mixed with view concerns
const joinDate = new Date(user.created_at);
const metadata = user.metadata ?? {};
return <div>{user.email}</div>;
}When the API changes created_at to a Unix timestamp, every file that imports UserDTO must update. The domain service breaks when it expects a date object but receives a number. Components fail when they parse the timestamp as an ISO string. The database layer needs different field names (createdAt in Postgres) but uses the same type. No layer can evolve without coordinating changes across the entire codebase.
The TypeScript handbook documents type inference and structural typing in Everyday Types, but structural typing alone cannot enforce architectural boundaries. Without explicit separation, nothing prevents a component from depending on internal DTO fields that the API team plans to deprecate.
%% alt: Diagram showing DTO reuse creating tight coupling
flowchart TD
A("UserDTO type") --> B("Domain Service")
A --> C("API Route Handler")
A --> D("React Component")
A --> E("Database Query")
E --> F("snake_case conflicts")
C --> G("API versioning impossible")
style F stroke:#fbbf24,fill:#3a2f0b,color:#fef3c7
style G stroke:#fbbf24,fill:#3a2f0b,color:#fef3c7

Layer 1: Domain Types: Your Business Logic Source of Truth
Domain types define business entities independent of infrastructure concerns. These types represent what the application does, not how data moves between systems. A User domain type contains fields the business logic needs to make decisions, expressed in terms that match the problem space rather than the database schema.
// Domain types define business concepts
interface User {
id: UserId;
email: EmailAddress;
registeredAt: Date;
subscription: Subscription | null;
}
type UserId = string & { readonly __brand: 'UserId' };
type EmailAddress = string & { readonly __brand: 'EmailAddress' };
interface Subscription {
plan: 'free' | 'pro' | 'enterprise';
expiresAt: Date;
autoRenew: boolean;
}
// Domain logic operates on domain types
class UserDomain {
canAccessFeature(user: User, feature: string): boolean {
if (user.subscription === null) return false;
if (user.subscription.expiresAt < new Date()) return false;
return this.planIncludes(user.subscription.plan, feature);
}
private planIncludes(plan: Subscription['plan'], feature: string): boolean {
// Business rules about plan capabilities
return plan !== 'free';
}
}Domain types use nominal typing patterns (branded types) to prevent mixing incompatible values. A UserId cannot be accidentally used where an OrderId is expected even though both are strings at runtime. The registeredAt field uses Date objects because domain logic compares dates, not ISO strings. The subscription field is nullable at the domain level because the business rule "users without subscriptions have limited access" requires representing the absence of a subscription.
This domain model never references transport format. It does not know that the backend sends created_at as an ISO string or that the database stores registered_at as a timestamp. Domain types remain stable when infrastructure details change. The API can switch from ISO strings to Unix timestamps without touching UserDomain.
%% alt: Diagram showing domain types at the core with no external dependencies
flowchart TD
A("User domain type") --> B("Business logic methods")
A --> C("Domain validation rules")
A --> D("Invariants enforced")
B --> E("No infrastructure knowledge")
C --> E
D --> E
style A stroke:#c084fc,fill:#3b0764,color:#f3e8ff,stroke-width:4px
The TypeScript 4.6 release notes document control flow analysis for destructured discriminated unions, which helps domain types use discriminated unions for modeling different entity states. A Subscription can be ActiveSubscription | ExpiredSubscription | CanceledSubscription and destructuring the discriminant narrows the type correctly.
Layer 2: DTO Types: Transport Contracts That Never Leak
DTO types define wire format contracts. These types describe exactly what crosses the network boundary, using the naming conventions and serialization formats the API specifies. A DTO type documents what the HTTP response body contains, not what the application does with that data.
// DTOs match API wire format exactly
interface UserDTO {
id: string;
email: string;
created_at: string; // ISO 8601 string
subscription: SubscriptionDTO | null;
}
interface SubscriptionDTO {
plan: string;
expires_at: string; // ISO 8601 string
auto_renew: boolean;
}
// DTOs never escape the API boundary
class UserAPI {
async fetchUser(id: string): Promise<UserDTO> {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
// Mapper translates DTO to domain type
toDomain(dto: UserDTO): User {
return {
id: dto.id as UserId,
email: dto.email as EmailAddress,
registeredAt: new Date(dto.created_at),
subscription: dto.subscription ? {
plan: this.parsePlan(dto.subscription.plan),
expiresAt: new Date(dto.subscription.expires_at),
autoRenew: dto.subscription.auto_renew,
} : null,
};
}
private parsePlan(plan: string): Subscription['plan'] {
if (plan === 'free' || plan === 'pro' || plan === 'enterprise') {
return plan;
}
throw new Error(`Unknown plan: ${plan}`);
}
}The UserDTO type uses created_at and expires_at with underscores because that matches the API convention. These fields are strings because JSON serialization represents dates as ISO 8601 strings. The plan field is a loose string rather than a discriminated union because the API does not guarantee a fixed set of values, and production logs show occasional typos in backend responses.
DTOs remain stable when domain logic changes. If the domain adds a computed isActive property that derives from expiresAt, the DTO does not change because the API does not send that field. The mapper handles the conversion from transport format to business format, absorbing differences in naming conventions and type representations.
This boundary prevents leaking API versioning details into the domain. When the API introduces a /v2/users endpoint that sends registration_date instead of created_at, the application adds a new UserDTOv2 type and a corresponding mapper. Domain types remain unchanged because they represent business concepts, not API versions.
Layer 3: API Types: Versioned Contracts and Breaking Change Management
API types define external contracts that clients depend on. These types version separately from internal implementation and enforce backward compatibility guarantees. A breaking change in an API type requires a new version endpoint, while internal domain changes do not affect the API contract.
// API v1 types define the public contract
namespace APIv1 {
export interface GetUserResponse {
id: string;
email: string;
created_at: string;
subscription: {
plan: 'free' | 'pro' | 'enterprise';
expires_at: string;
auto_renew: boolean;
} | null;
}
export interface UpdateUserRequest {
email?: string;
}
}
// API v2 adds fields without breaking v1
namespace APIv2 {
export interface GetUserResponse {
id: string;
email: string;
username: string; // New field
created_at: string;
subscription: {
plan: 'free' | 'pro' | 'enterprise';
expires_at: string;
auto_renew: boolean;
features: string[]; // New field
} | null;
}
export interface UpdateUserRequest {
email?: string;
username?: string; // New field
}
}
// API route handler maps from domain to API types
class UserAPIHandler {
async handleGetUser(req: Request): Promise<APIv2.GetUserResponse> {
const user = await this.userService.findUser(req.params.id);
return this.toAPIv2(user);
}
private toAPIv2(user: User): APIv2.GetUserResponse {
return {
id: user.id,
email: user.email,
username: this.generateUsername(user.email),
created_at: user.registeredAt.toISOString(),
subscription: user.subscription ? {
plan: user.subscription.plan,
expires_at: user.subscription.expiresAt.toISOString(),
auto_renew: user.subscription.autoRenew,
features: this.getFeaturesForPlan(user.subscription.plan),
} : null,
};
}
private generateUsername(email: string): string {
return email.split('@')[0];
}
private getFeaturesForPlan(plan: string): string[] {
// Map plan to feature list
return [];
}
}The APIv1 and APIv2 namespaces isolate version-specific types. Routes serving /v1/users use APIv1.GetUserResponse, while routes serving /v2/users use APIv2.GetUserResponse. Both versions map from the same domain User type, but each version exposes different fields and applies different transformations.
This separation allows adding features without breaking existing clients. When the API adds username and features fields to v2, v1 clients continue receiving responses that match APIv1.GetUserResponse. The domain User type does not need a username field because that value derives from the email address. API types can be richer or simpler than domain types depending on client requirements.
API types enforce contracts through explicit typing. If a developer accidentally removes a required field from APIv2.GetUserResponse, TypeScript reports an error in the route handler where the response no longer matches the declared type. This compile-time check prevents shipping breaking changes to production.

Layer 4: UI Types: View Models That Mirror Components, Not the Domain
UI types define shapes that components consume. These types optimize for rendering requirements rather than business logic structure. A component that displays a user profile needs formatted strings and boolean flags for visibility, not domain entities with complex validation rules.
// UI types match component requirements
interface UserProfileViewModel {
displayName: string;
emailAddress: string;
memberSince: string; // "Member since Nov 2024"
subscriptionBadge: {
text: string;
variant: 'default' | 'premium' | 'enterprise';
} | null;
canUpgrade: boolean;
}
// Mapper translates domain to view model
class UserProfileMapper {
toViewModel(user: User): UserProfileViewModel {
return {
displayName: this.formatDisplayName(user.email),
emailAddress: user.email,
memberSince: this.formatMemberSince(user.registeredAt),
subscriptionBadge: this.formatSubscriptionBadge(user.subscription),
canUpgrade: user.subscription === null || user.subscription.plan === 'free',
};
}
private formatDisplayName(email: string): string {
return email.split('@')[0];
}
private formatMemberSince(date: Date): string {
return `Member since ${date.toLocaleDateString('en-US', {
month: 'short',
year: 'numeric'
})}`;
}
private formatSubscriptionBadge(
subscription: Subscription | null
): UserProfileViewModel['subscriptionBadge'] {
if (subscription === null) return null;
const variantMap: Record<Subscription['plan'], 'default' | 'premium' | 'enterprise'> = {
free: 'default',
pro: 'premium',
enterprise: 'enterprise',
};
return {
text: subscription.plan.toUpperCase(),
variant: variantMap[subscription.plan],
};
}
}
// Component uses view model type
function UserProfile({ viewModel }: { viewModel: UserProfileViewModel }) {
return (
<div>
<h2>{viewModel.displayName}</h2>
<p>{viewModel.emailAddress}</p>
<p>{viewModel.memberSince}</p>
{viewModel.subscriptionBadge && (
<Badge variant={viewModel.subscriptionBadge.variant}>
{viewModel.subscriptionBadge.text}
</Badge>
)}
{viewModel.canUpgrade && <UpgradeButton />}
</div>
);
}The UserProfileViewModel contains only the data the component renders. The memberSince field is a pre-formatted string because the component does not perform date calculations. The subscriptionBadge structure matches the Badge component's props exactly, including the variant union that determines styling. The canUpgrade boolean replaces business logic that checks subscription status and expiration.
This decoupling allows changing component requirements without touching domain logic. If designers want to show subscription status as an icon instead of a badge, the view model changes but the domain User type remains stable. If the domain adds subscription tiers, the mapper absorbs the complexity and continues providing the same view model shape to components.
UI types prevent components from depending on business rules. When a component receives canUpgrade: true, it displays an upgrade button without knowing why upgrade is allowed. The business logic that determines eligibility lives in the domain layer, and the mapper translates the decision into a simple boolean. Components become pure presentation logic that transforms view models into DOM elements.
For applications using template literal types to enforce type-safe string patterns, template literal types documentation covers branded string types that prevent mixing incompatible values across layers.
Mapping Between Layers: The Boundaries That Prevent Cascading Changes
Mapper functions enforce boundaries between layers by translating types at architectural edges. Each mapper sits at a single boundary and converts between adjacent layers. The API-to-domain mapper translates DTOs to domain types. The domain-to-UI mapper translates domain types to view models. No mapper crosses multiple boundaries.
// Mappers sit at layer boundaries
class UserMapper {
// API layer → Domain layer
apiToDomain(dto: UserDTO): User {
return {
id: dto.id as UserId,
email: dto.email as EmailAddress,
registeredAt: new Date(dto.created_at),
subscription: dto.subscription ? this.mapSubscription(dto.subscription) : null,
};
}
private mapSubscription(dto: SubscriptionDTO): Subscription {
return {
plan: this.validatePlan(dto.plan),
expiresAt: new Date(dto.expires_at),
autoRenew: dto.auto_renew,
};
}
private validatePlan(plan: string): Subscription['plan'] {
const valid = ['free', 'pro', 'enterprise'];
if (!valid.includes(plan)) {
throw new Error(`Invalid plan: ${plan}`);
}
return plan as Subscription['plan'];
}
// Domain layer → UI layer
domainToViewModel(user: User): UserProfileViewModel {
return {
displayName: this.extractDisplayName(user.email),
emailAddress: user.email,
memberSince: this.formatDate(user.registeredAt),
subscriptionBadge: this.formatBadge(user.subscription),
canUpgrade: this.determineUpgradeEligibility(user),
};
}
private extractDisplayName(email: EmailAddress): string {
return email.split('@')[0];
}
private formatDate(date: Date): string {
return `Member since ${date.toLocaleDateString('en-US', {
month: 'short',
year: 'numeric'
})}`;
}
private formatBadge(
subscription: Subscription | null
): UserProfileViewModel['subscriptionBadge'] {
if (!subscription) return null;
return {
text: subscription.plan.toUpperCase(),
variant: this.mapPlanToVariant(subscription.plan),
};
}
private mapPlanToVariant(plan: Subscription['plan']): 'default' | 'premium' | 'enterprise' {
const mapping = { free: 'default', pro: 'premium', enterprise: 'enterprise' } as const;
return mapping[plan];
}
private determineUpgradeEligibility(user: User): boolean {
return user.subscription === null || user.subscription.plan === 'free';
}
}%% alt: Diagram showing data flow through mapper boundaries
flowchart LR
A("API DTO") --> B("API-Domain Mapper")
B --> C("Domain Type")
C --> D("Domain-UI Mapper")
D --> E("View Model")
E --> F("Component renders")
style C stroke:#c084fc,fill:#3b0764,color:#f3e8ff,stroke-width:4px
style F stroke:#34d399,fill:#0b3b2e,color:#d1fae5
Mappers absorb format differences between layers. The apiToDomain mapper converts ISO strings to Date objects, validates plan values against the domain enum, and applies branded types. The domainToViewModel mapper pre-formats dates, flattens nested structures for display, and derives boolean flags from business rules. These transformations prevent leaking format details across boundaries.
When the API changes created_at to a Unix timestamp, only the apiToDomain mapper changes. The domain User type continues using Date objects because that matches how business logic operates. Components continue receiving formatted date strings because the domainToViewModel mapper handles conversion. The change remains localized to the boundary where it occurs.
Mappers also handle validation and error cases at boundaries. If the API sends an invalid plan value, the validatePlan method throws an error at the API-domain boundary rather than allowing invalid data into the domain layer. If the domain adds new subscription tiers, the mapPlanToVariant method maps unfamiliar values to a default variant rather than breaking component rendering.
For global type definitions that need careful boundary management, globalThis typing patterns demonstrate how to isolate ambient types from application types.
| Layer transition | Mapper responsibility | Failure mode without mapper |
|---|---|---|
| API → Domain | Parse transport format, validate invariants, apply branded types | Invalid data enters business logic, causing silent failures |
| Domain → UI | Format for display, flatten structures, derive flags | Components duplicate business logic, breaking when rules change |
| Domain → API | Serialize domain types, apply version-specific transformations | Breaking changes cascade to external clients |
| DTO → API | Version API responses independently of internal DTOs | Cannot evolve internal types without breaking clients |
The TypeScript handbook covers mapped types that help build transformation utilities. A Partial<T> mapped type generates optional versions of domain types for update operations, while custom mapped types can enforce naming conventions across layers.
Enforcing Boundaries: Lint Rules, Project References, and File Organization
Architectural boundaries require active enforcement because TypeScript's structural type system does not prevent importing types across layers. Without constraints, developers import DTOs into components, breaking the separation between transport format and UI concerns. Three mechanisms enforce boundaries: ESLint rules, TypeScript project references, and file system organization.
ESLint rules prevent importing types from the wrong layer. The @typescript-eslint/no-restricted-imports rule blocks importing DTO types in domain or UI code. Configure the rule to match your layer structure:
// .eslintrc.js
module.exports = {
rules: {
'@typescript-eslint/no-restricted-imports': ['error', {
patterns: [
{
group: ['**/dto/*'],
message: 'DTOs cannot be imported outside the API boundary',
},
{
group: ['**/domain/*'],
importNames: ['*DTO'],
message: 'Domain types must not reference DTOs',
},
],
}],
},
};TypeScript project references enforce dependency direction at build time. Split the codebase into separate tsconfig.json files for each layer. The domain project references no other projects. The API project references only the domain project. The UI project references domain and API projects but not DTO internals.
// packages/domain/tsconfig.json
{
"compilerOptions": {
"composite": true,
"outDir": "dist"
},
"include": ["src/**/*"]
}
// packages/api/tsconfig.json
{
"compilerOptions": {
"composite": true,
"outDir": "dist"
},
"references": [
{ "path": "../domain" }
],
"include": ["src/**/*"]
}
// packages/ui/tsconfig.json
{
"compilerOptions": {
"composite": true,
"outDir": "dist"
},
"references": [
{ "path": "../domain" }
],
"include": ["src/**/*"]
}File organization makes layer boundaries visible. Group files by layer rather than feature. Each layer exports only its public types through an index.ts file, preventing direct imports of internal implementation.
src/
├── domain/
│ ├── user/
│ │ ├── user.types.ts # Domain types
│ │ ├── user.service.ts # Business logic
│ │ └── index.ts # Public exports only
│ └── index.ts
├── api/
│ ├── dto/
│ │ ├── user.dto.ts # Wire format types
│ │ └── index.ts # Internal, not exported
│ ├── mappers/
│ │ ├── user.mapper.ts # DTO → Domain
│ │ └── index.ts
│ └── index.ts
└── ui/
├── view-models/
│ ├── user.view-model.ts # UI types
│ └── index.ts
├── mappers/
│ ├── user.mapper.ts # Domain → ViewModel
│ └── index.ts
└── index.ts
Each layer's index.ts exports only stable contracts. The domain layer exports domain types and service interfaces. The API layer exports versioned API types and client methods. The UI layer exports view model types and mapper functions. Internal DTO types remain private to the API layer.
This structure prevents accidental coupling. When a developer tries to import UserDTO in a component, the import path ../../api/dto/user.dto signals a boundary violation. The correct import ../../ui/view-models/user.view-model guides developers toward the intended architecture.
For function overload patterns that help define clear mapper signatures, TypeScript function overloads covers techniques for type-safe transformations between layers.
Comparison: Single-Type vs Four-Layer Architecture
| Aspect | Single DTO everywhere | Four-layer architecture |
|---|---|---|
| Change isolation | Backend field rename breaks all layers | Changes localized to affected boundary |
| Type safety | Structural typing allows silent misuse | Branded types prevent layer mixing |
| API versioning | Breaking changes cascade to UI | New versions coexist with old contracts |
| Domain evolution | Business rules coupled to transport format | Domain types evolve independently |
| Component testing | Tests depend on API response shape | Tests use stable view model fixtures |
| Refactoring blast radius | Entire codebase | Single layer plus boundary mappers |
Frequently Asked Questions
When should a team adopt the four-layer architecture instead of simpler patterns?
Teams should adopt four-layer architecture when API contracts version independently of internal features, multiple clients consume the same backend, or domain logic changes frequently without affecting UI structure. Smaller applications with tight frontend-backend coupling benefit less from the additional mapping overhead.
How do mappers handle optional fields that exist in some layers but not others?
Mappers use explicit logic to add or remove optional fields at boundaries. When mapping domain to UI, the mapper can add computed fields (like canUpgrade) that do not exist in the domain type. When mapping API to domain, the mapper can discard fields (like debug metadata) that the domain does not need.
What happens when a mapper needs to call async operations during transformation?
Mappers that require async operations (like fetching related entities) should return promises and perform those operations within the mapper boundary. The caller awaits the mapped result. Avoid making mappers stateful or caching results, as that creates hidden dependencies between layers.
How should teams handle types that appear identical across multiple layers?
Even when types appear structurally identical, maintain separate definitions at each layer. This allows layers to evolve independently when requirements diverge. Use type aliases or utility types to reduce duplication while keeping layer boundaries explicit.
Do all applications need all four layers?
Applications without external API contracts can merge the DTO and API layers into a single transport layer. Applications with simple UI requirements can merge the UI layer into the domain layer. The critical boundary is between domain types and transport format, as that separation prevents infrastructure details from affecting business logic.
The four-layer type architecture establishes ownership at each boundary. Domain types define business rules independent of infrastructure. DTOs define wire contracts that never leak beyond the API boundary. API types version external contracts separately from internal implementation. UI types mirror component requirements without knowledge of backend structure. Mapping functions translate between these representations, absorbing format differences and validation at architectural edges. This separation prevents changes in one layer from cascading through the entire application. When the backend renames a field, the DTO changes but mappers absorb the difference. When designers change component layout, view models change but domain types remain stable. The result is a codebase where each layer evolves independently and changes remain localized to the boundary where they occur.