Type-Safe Data Transformations with TypeScript
Make data transformations trustworthy with branded types, total parsers, and Result types that keep errors in the type system instead of the call stack.
On this page
Introduction
TypeScript’s type system is erased at runtime, which means a variable typed as User is only a User if the code that produced it actually produced one. The most common source of production bugs in a typed codebase is the boundary where untyped data enters the typed world — an API response, a JSON file, a form payload — and is assigned a type with an unchecked cast. The data is typed as User but it is actually unknown with a hopeful annotation, and the first property access on a missing field throws at runtime. Type-safe data transformations close this gap with branded types that distinguish values that look the same, total parsers that turn unknown into a typed value or an error, and Result types that keep the error in the type system rather than the call stack. This article builds those tools and the discipline of using them at every boundary.
The Boundary Problem
Every application has a boundary where data it did not create enters it: a network response, a parsed JSON body, a value from localStorage. At that boundary the data is unknown — TypeScript has no way to know the shape of bytes that arrived over the network. The dangerous move is the assertion: const user = response as User. This compiles, and it lies. The runtime value is whatever the network sent, and the type says it is a User, and the first time a field is missing the lie is exposed as a runtime error in code that the type system promised was safe.
// The lie: the cast promises a shape nobody verified.
const user = (await fetch("/api/me").then(r => r.json())) as User;
console.log(user.profile.email.toUpperCase()); // TypeError if profile or email is missing
The fix is to never assert at a boundary and always to parse. Parsing is a function from unknown to either a typed value or an error, and it runs at runtime. If it returns the typed value, the type is honest because the runtime checked it. If it returns an error, you handle it explicitly. The type system and the runtime agree, because the runtime is the source of the type.
Branded Types: Distinguishing Values That Look the Same
A branded type uses a unique phantom property to distinguish values that have the same runtime representation but different meanings. A UserId and an OrderId are both strings at runtime, but confusing one for the other is a bug the type system should catch. A branded type makes them incompatible at compile time while preserving the string at runtime.
declare const brand: unique symbol;
type Brand<T, B> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type Email = Brand<string, "Email">;
// Constructors are the only way to create a branded value, and they validate.
function userId(s: string): UserId {
if (!s.startsWith("user_")) throw new Error("invalid user id");
return s as UserId;
}
function email(s: string): Email {
if (!/^[^@]+@[^@]+\.[^@]+$/.test(s)) throw new Error("invalid email");
return s as Email;
}
function fetchUser(id: UserId): Promise<User> { /* ... */ }
fetchUser(orderIdValue); // compile error: OrderId is not assignable to UserId
The brand is erased at runtime — it is a type-level marker, not a real property — so there is no runtime cost. The value is still a string, but the type system refuses to pass it where a different brand is expected. The constructor is the gatekeeper: the only way to produce a UserId is through userId(), which validates, so a UserId in the code is a string that is known to start with user_. This pattern turns “this string is an id” from a comment into a compile-time guarantee.
Total Parsers with Zod
A parser is total if it returns a result for every input — never throws, never returns undefined. Zod’s safeParse is a total parser: it returns { success: true, data } or { success: false, error } for any input, and the data is typed. This is the function to use at every boundary.
import { z } from "zod";
const UserSchema = z.object({
id: z.string().regex(/^user_/),
email: z.string().email(),
profile: z.object({
name: z.string().min(1),
age: z.number().int().min(0).max(150),
}),
});
type User = z.infer<typeof UserSchema>;
// Total parser: unknown -> { success, data | error }
function parseUser(input: unknown): z.SafeParseReturnType<User> {
return UserSchema.safeParse(input);
}
async function getUser(): Promise<User> {
const raw = await fetch("/api/me").then(r => r.json());
const result = parseUser(raw);
if (!result.success) {
throw new Error(`bad user shape: ${result.error.issues.map(i => i.path.join(".")).join(", ")}`);
}
return result.data; // typed as User, and honestly so
}
The schema is the single source of truth for the shape, and z.infer derives the type from it, so the type and the runtime check cannot drift. Parse at the boundary, and downstream code receives an honestly typed value. The error from safeParse is structured — it tells you which field failed and why — so you can map it to a user-facing message or a log entry without parsing a stack trace.
The Result Type: Errors in the Type, Not the Stack
Exceptions are a control-flow mechanism that is invisible to the type system: a function that throws has no way to declare what it throws, and a caller has no way to know it must handle the throw. The Result type makes the error a part of the return type, so the caller cannot ignore it — the compiler enforces handling the way it enforces handling a nullable.
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function ok<T>(value: T): Result<T> { return { ok: true, value }; }
function err<E>(error: E): Result<never, E> { return { ok: false, error }; }
// A function that can fail declares it in the return type.
function parseInt(s: string): Result<number, "not-an-int"> {
const n = Number(s);
return Number.isInteger(n) ? ok(n) : err("not-an-int");
}
// The caller must handle both branches; the compiler enforces it.
const n = parseInt(input);
if (n.ok) {
useNumber(n.value);
} else {
showError(n.error); // typed as "not-an-int"
}
Use Result for expected failures — a parse error, a not-found, a validation failure — where the caller has a meaningful recovery path. Use exceptions for unexpected failures — a null dereference, a violated invariant — where the failure is a bug and the right response is to crash the operation and alert a human. Mixing them (throwing for expected failures) forces every caller to wrap every call in a try/catch to handle cases the type system did not warn them about, which is the world Result exists to avoid.
Composing Transformations Safely
Real transformations are pipelines: parse the input, validate it, transform it, serialize it. Each step can fail, and the Result type lets you compose them so a failure short-circuits the pipeline and the type tracks the error at each stage.
function map<T, U, E>(r: Result<T, E>, f: (v: T) => U): Result<U, E> {
return r.ok ? ok(f(r.value)) : r;
}
function andThen<T, U, E>(r: Result<T, E>, f: (v: T) => Result<U, E>): Result<U, E> {
return r.ok ? f(r.value) : r;
}
// A pipeline where each step's failure is tracked in the type.
const result = andThen(
map(parseUser(raw), normalizeUser),
persistUser, // (user: User) => Result<SavedUser, "db-error">
);
if (!result.ok) handleError(result.error); // error is "db-error" | ZodError
The composition is total: every input produces a result, and the error type accumulates the failure modes of every step. There is no unhandled throw, no unchecked cast, no field access on a value the runtime did not verify. The pipeline is a function whose type tells you exactly what it can return and what it can fail with, and the compiler enforces that you handle both.
Parsing at Every Boundary and Code Generation from Schemas
The principle that makes a TypeScript codebase genuinely type-safe is parse, don’t validate: at every boundary where data of unknown shape enters the typed world, run it through a parser that either produces a value of the known type or rejects. The boundaries are the HTTP request body, the query string, the environment variables, the message from the queue, the row from the database, the response from an external API. At each, a Zod schema (or equivalent) parses the input and the result is a value the compiler knows is the right type. Between the boundaries, the types flow through the pure functions without runtime checks, because the parser already guaranteed the shape.
// The boundary: parse the request body into a typed value.
const body = UserCreateSchema.parse(req.body); // throws on invalid -> 400
// Between boundaries: pure functions with no runtime checks.
const user = applyDefaults(body);
const saved = await repo.create(user);
// The next boundary: parse the database row back out.
return UserSchema.parse(saved); // catches drift between the code and the schema
The second parse — parsing the database row back out — is the one teams skip and the one that catches the most bugs. A database row that has a column the code does not expect (added by a migration not yet deployed) or a column that is null where the code assumes non-null is a runtime crash waiting for the first request that reads it. Parsing the row through the schema on read catches the drift at the boundary, with a clear error, rather than at the first property access in the depths of the business logic. The cost is a parse per query; the benefit is that the database and the code cannot silently disagree.
For data that crosses a boundary you do not control — an external API, a webhook from a third party — the parse is the defense. The external system’s documentation says the field is a string, but the parse catches the day it is a number, or null, or absent. Treat the external system’s types as a suggestion, not a guarantee, and let the parser be the authority. When the external system changes its response in a way the schema does not accept, the parse fails loudly with the field and the expected type, and you fix the schema before the users see the breakage. Without the parse, the change manifests as a TypeError in production at 3 AM.
Code generation from the schema closes the loop between the schema and the types, so they cannot drift. When the schema is the source of truth, the TypeScript types are generated from it (z.infer<typeof UserSchema>), the database migrations are generated from it, the OpenAPI spec is generated from it, and the client types are generated from the spec. Every artifact traces back to the schema, and a change to the schema propagates to every consumer at the next build. This is the opposite of maintaining the types, the schema, the migrations, and the spec by hand and hoping they agree — with generation, they agree by construction.
// The schema is the source of truth; the type is derived, not written.
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(["admin", "member", "viewer"]),
createdAt: z.coerce.date(),
});
type User = z.infer<typeof UserSchema>; // { id: string; email: string; role: "admin" | "member" | "viewer"; createdAt: Date }
// The database column types can be generated from the same schema,
// so the migration and the code cannot disagree about whether email is nullable.
For a full-stack application, the schema lives in a shared package that both the server and the client import. The server uses it to parse request bodies and database rows; the client uses it to parse API responses and to drive form validation. The inferred type is the same on both sides, compiled from the same schema, so a field added on the server is immediately visible to the client’s type checker. This shared-schema architecture is the strongest form of end-to-end type safety, and it is the pattern that makes a refactor safe: change the schema, and the compiler tells you every server and every client location that needs to change, with no runtime surprises.
Conclusion
Type-safe data transformations rest on three tools: branded types that distinguish values of the same runtime shape, total parsers that turn unknown into an honestly typed value or a structured error at every boundary, and Result types that make expected failures a part of the return type the compiler enforces. The discipline is to never cast at a boundary, to parse every value that crosses one, and to compose transformations so the type tracks both the success and the error through the pipeline. The payoff is a codebase where the type system’s promises are true at runtime — where a User is a user because something checked, not because something asserted — and where the failures the type system warns you about are the failures you actually handle.
Report a problem with this articleOpens a pre-filled issue on GitHub.