Anti-Corruption Layers in TypeScript
An anti-corruption layer translates an outside system's data into your own model at the boundary. See validation, mapping and error handling in TypeScript.

An anti-corruption layer is a piece of code at the edge of your application that translates between an external system's model and your own, so the outside shape never leaks into your core. A partner API with cryptic field names, a legacy service with odd conventions or a third-party SDK with its own vocabulary stays confined to one module, and the rest of your code works with types you designed. This post builds one in TypeScript 5.9 on Node.js 24: untrusted input checked with type guards, a mapper to a clean domain type, explicit handling of bad data, and the testing approach that keeps the boundary honest.
The problem: foreign shapes spreading inward
A legacy customer service returns data like this, and the first developer to consume it uses the fields directly.
interface LegacyCustomer {
CUST_ID: string;
CUST_NM: string;
EMAIL: string;
STATUS: string;
BIRTH: string;
}
function greeting(c: LegacyCustomer): string {
return `Hello ${c.CUST_NM.trim()}`;
}
function canOrder(c: LegacyCustomer): boolean {
return c.STATUS === "A" && c.EMAIL !== "N/A";
}Both functions know the legacy conventions: that names are padded with spaces, that "A" means active and that "N/A" stands for a missing email. Every function that touches a customer repeats that knowledge. When the legacy service changes "A" to "ACTIVE", or when you replace it with a new service, every one of those functions must change, and nothing tells you which ones.
Step 1: define your own model
Design the type your application wishes it received, free of the legacy quirks.
export type CustomerStatus = "active" | "inactive" | "suspended";
export interface Customer {
id: number;
name: string;
email: string | null;
status: CustomerStatus;
birthDate: Date;
}Notice what changed: id is a number, a missing email is null and not a magic string, status has a closed set of readable values and the birth date is a Date. The rest of the application depends only on this file.
Step 2: check the input, because types do not exist at run time
TypeScript types are erased when the code runs. A response typed as LegacyCustomer is only a promise, and the legacy service can break it. At the boundary, treat data as unknown and verify it.
export interface LegacyCustomer {
CUST_ID: string;
CUST_NM: string;
EMAIL: string;
STATUS: string;
BIRTH: string;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
export function isLegacyCustomer(value: unknown): value is LegacyCustomer {
return (
isRecord(value) &&
typeof value.CUST_ID === "string" &&
typeof value.CUST_NM === "string" &&
typeof value.EMAIL === "string" &&
typeof value.STATUS === "string" &&
typeof value.BIRTH === "string"
);
}
console.log(isLegacyCustomer({ CUST_ID: "7", CUST_NM: "Ada", EMAIL: "[email protected]", STATUS: "A", BIRTH: "18151210" }));
console.log(isLegacyCustomer({ CUST_ID: 7 }));
console.log(isLegacyCustomer(null));true
false
falseThe guard narrows unknown to LegacyCustomer after it returns true, so the mapper that follows gets a checked type. For larger schemas, a validation library such as Zod keeps this shorter, and the principle is the same: validate once at the edge and trust the result inside.
Step 3: translate
The mapper is the heart of the layer. It is the only place that knows both vocabularies.
import type { Customer, CustomerStatus } from "./domain.ts";
import { isLegacyCustomer } from "./guard.ts";
const STATUS: Record<string, CustomerStatus> = {
A: "active",
I: "inactive",
S: "suspended",
};
export function toCustomer(raw: unknown): Customer {
if (!isLegacyCustomer(raw)) {
throw new Error("legacy customer has an unexpected shape");
}
const status = STATUS[raw.STATUS];
if (!status) throw new Error(`unknown legacy status "${raw.STATUS}"`);
const match = /^(\d{4})(\d{2})(\d{2})$/.exec(raw.BIRTH);
if (!match) throw new Error(`bad birth date "${raw.BIRTH}"`);
const [, year, month, day] = match;
return {
id: Number(raw.CUST_ID),
name: raw.CUST_NM.trim(),
email: raw.EMAIL === "N/A" ? null : raw.EMAIL,
status,
birthDate: new Date(Date.UTC(Number(year), Number(month) - 1, Number(day))),
};
}
const customer = toCustomer({
CUST_ID: "00042",
CUST_NM: "Ada Lovelace ",
EMAIL: "N/A",
STATUS: "A",
BIRTH: "18151210",
});
console.log(JSON.stringify(customer));{"id":42,"name":"Ada Lovelace","email":null,"status":"active","birthDate":"1815-12-10T00:00:00.000Z"}Each legacy convention is handled once: padded names are trimmed, the "N/A" sentinel becomes null, the status code becomes a readable union member and the compact date becomes a Date. Months in Date.UTC are zero-based, which is why the mapper subtracts one.
Step 4: decide what bad data means
A strict mapper throws on anything unexpected, which is the safe default, since silently guessing about a customer's status could be worse than failing. But one bad record should not take down a batch of thousands. Collect failures separately and let the caller decide.
import { toCustomer } from "./mapper.ts";
import type { Customer } from "./domain.ts";
export function toCustomers(rows: unknown[]): { ok: Customer[]; errors: string[] } {
const ok: Customer[] = [];
const errors: string[] = [];
rows.forEach((row, index) => {
try {
ok.push(toCustomer(row));
} catch (err) {
errors.push(`row ${index}: ${(err as Error).message}`);
}
});
return { ok, errors };
}
const result = toCustomers([
{ CUST_ID: "1", CUST_NM: "Ada", EMAIL: "[email protected]", STATUS: "A", BIRTH: "18151210" },
{ CUST_ID: "2", CUST_NM: "Lin", EMAIL: "[email protected]", STATUS: "Z", BIRTH: "19900101" },
{ CUST_ID: "3" },
]);
console.log(result.ok.length);
console.log(result.errors);1
[
'row 1: unknown legacy status "Z"',
'row 2: legacy customer has an unexpected shape'
]The first row passed, and the other two were reported with their position. The caller can log the errors, alert on a rate of failures or abort the whole batch when the failure rate suggests the service has changed its contract. That last case is an important signal: a sudden wave of "unknown status" errors means the outside world changed, and the layer's job is to make that visible at the boundary, and not three modules later.
Step 5: translate outgoing calls too
The layer works in both directions. When your code writes to the legacy system, it should hand over a Customer and let the layer produce whatever the outside format needs.
import type { Customer } from "./domain.ts";
const STATUS_CODES = { active: "A", inactive: "I", suspended: "S" } as const;
export function toLegacyUpdate(customer: Customer): Record<string, string> {
const pad = (n: number, width: number) => String(n).padStart(width, "0");
const d = customer.birthDate;
return {
CUST_ID: pad(customer.id, 5),
CUST_NM: customer.name,
EMAIL: customer.email ?? "N/A",
STATUS: STATUS_CODES[customer.status],
BIRTH: `${pad(d.getUTCFullYear(), 4)}${pad(d.getUTCMonth() + 1, 2)}${pad(d.getUTCDate(), 2)}`,
};
}
const update = toLegacyUpdate({
id: 42,
name: "Ada Lovelace",
email: null,
status: "suspended",
birthDate: new Date(Date.UTC(1815, 11, 10)),
});
console.log(update);{
CUST_ID: '00042',
CUST_NM: 'Ada Lovelace',
EMAIL: 'N/A',
STATUS: 'S',
BIRTH: '18151210'
}The as const on the status table makes the lookup type-safe: indexing it with a CustomerStatus returns a literal type, and adding a fourth status to the domain type without adding it here is a compile error. This is where TypeScript earns its keep at the boundary.
Where the layer lives
Put the layer in its own folder or package, such as integrations/legacy-customers/, with a small public surface: functions that return domain types, and nothing else exported. Enforce this with an import rule in your linter, so code outside the folder cannot import LegacyCustomer. If the legacy type is not visible, nobody can use it by accident.
The layer should contain the HTTP client or SDK call too, not only the mapping. A function fetchCustomer(id): Promise<Customer> hides the transport, the field names and the error format behind one call. Callers get a domain object or a typed failure, and swapping the legacy service for a new one means rewriting one folder.
Testing the boundary
The mapper is a pure function, so it is easy to test, and its tests double as documentation of the legacy quirks. Use captured real responses as fixtures, including the strange ones.
import assert from "node:assert/strict";
import { test } from "node:test";
import { toCustomer } from "./mapper.ts";
test("padded names and N/A emails are normalized", () => {
const c = toCustomer({
CUST_ID: "9", CUST_NM: " Lin ", EMAIL: "N/A", STATUS: "I", BIRTH: "19900101",
});
assert.equal(c.name, "Lin");
assert.equal(c.email, null);
assert.equal(c.status, "inactive");
});
test("an unknown status is rejected, not guessed", () => {
assert.throws(
() => toCustomer({ CUST_ID: "9", CUST_NM: "Lin", EMAIL: "x", STATUS: "Q", BIRTH: "19900101" }),
/unknown legacy status "Q"/,
);
});✔ padded names and N/A emails are normalized (0.9ms)
✔ an unknown status is rejected, not guessed (0.3ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0Add a test whenever production shows a new quirk. The layer's test file becomes a record of everything unusual about the external system.
When not to use it
For a clean, stable external API that already matches your model, a mapping layer is ceremony. It earns its place when the outside model is awkward, when it changes without notice, when you expect to replace it or when its concepts differ from yours. A small prototype with one consumer of one endpoint can read the response directly and add the layer when the second consumer arrives.
Versioning and drift
External systems change without asking you. A field gets renamed, a new status appears, a date format shifts. The layer is where you notice. Log mapping failures with enough context to diagnose them, count them and alert when their rate rises above normal. A mapper that throws on an unknown status is doing its job when it fires, because the alternative is bad data flowing into your database and being discovered by a customer.
When the outside system publishes versions, support one at a time per mapper and name the files by version, such as mapper-v2.ts. During a migration you can run both mappers behind the same domain type, which lets you move consumers across gradually and compare the results. Because your core only sees Customer, nothing outside the layer needs to know which version produced it.
Keeping the domain type honest
The domain type should express what your application needs, not everything the outside system offers. Resist the urge to copy every field from the external model "just in case". Each field you adopt is a field you must map, test and maintain, and one you never read is dead weight. Add fields when a feature needs them, and the layer stays small and the mapping stays easy to review.


