Lesson 47 of 50TypeScript
Type Safety in Practice
Keep types honest in a real app by validating data at the edges, avoiding any and as, and modelling errors as values.
Types are only as good as the data that flows into them. A project can have strict on and zero compile errors, and still crash in production because an API returned null where the types said string. This lesson pulls the unit together into the habits that make a codebase actually safe: validate at the edges, trust types inside, and never lie to the compiler. These are the things senior reviewers look for in a pull request.
The edges are where types lie
Recall type erasure: at runtime, there are no types. Anything that comes from outside your code (an HTTP response, JSON.parse, localStorage, form data, environment variables, a message queue) has whatever shape it actually has, no matter what you annotate.
type User = { id: number; name: string };
async function getUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return res.json(); // res.json() returns Promise<any>, so this "works"
}
const user = await getUser(1);
user.name.toUpperCase(); // compiles. Crashes if the API sent { id: 1, name: null }The annotation Promise<User> is a claim nobody verified. The fix is a simple architecture rule:
Everything from outside enters as unknown. That forces a check before use.
unknown for external data, and why not as
The first step is to type outside data as unknown, not any. The compiler then refuses to let you use it until you check it.
const raw: unknown = await res.json();
raw.name;
// Error: 'raw' is of type 'unknown'.
const user = raw as User; // compiles... but checks nothingAn as cast (a type assertion) tells the compiler "trust me". It does no runtime work, so it is exactly as unsafe as any for external data. Treat as like a code smell: acceptable inside a small, tested helper, never as a substitute for validation. The worst form is the double cast x as unknown as Foo, which forces any type onto anything.
What does this print?
type Product = { name: string; priceCents: number };
const raw: unknown = JSON.parse('{"name": "Lamp", "price": 1999}');
const product = raw as Product;
console.log(`Total: ${product.priceCents * 2}`);Schema validation with Zod
Writing guards like isUser by hand gets tedious, and the guard and the type can drift apart. A schema library lets you declare the shape once as a runtime value, and infer the static type from it. Zod is the most popular in the TypeScript ecosystem (Valibot and ArkType are alternatives).
import { z } from "zod";
export const UserSchema = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
email: z.email(),
role: z.enum(["admin", "member"]),
bio: z.string().optional(),
});
export type User = z.infer<typeof UserSchema>;
// { id: number; name: string; email: string; role: "admin" | "member"; bio?: string }import { UserSchema, type User } from "@/lib/schemas/user";
export async function getUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
const data: unknown = await res.json();
return UserSchema.parse(data); // throws a ZodError with every problem listed
}
// Or without throwing:
const result = UserSchema.safeParse(data);
if (!result.success) {
console.error(result.error.issues); // [{ path: ["email"], message: "Invalid email address" }, ...]
} else {
result.data; // User
}One definition gives you a runtime validator and a type, so they cannot drift. The same pattern is used for form validation (React Hook Form resolvers), environment variables, and server actions. In FastAPI, Pydantic plays the same role.
Under the hood a schema is just a function from unknown to T that throws on bad input. You can build a tiny one yourself:
Press Run (⌘ Enter) to see what happens.z.infer<typeof UserSchema> instead of writing a User type by hand?Errors as values: Result types
throw is invisible in a function's type: nothing in parseConfig(text: string): Config tells the caller it might throw. For expected failures (invalid input, not found, payment declined), return a Result instead: a discriminated union that the caller must check.
Press Run (⌘ Enter) to see what happens.The caller cannot reach r.value without checking r.ok. Keep throw for unexpected failures (bugs, a database that is down) that should bubble up to an error boundary or a 500 handler.
Branded types and exhaustive switches
Structural typing has one weakness: a UserId and an OrderId are both just string, so swapping them compiles. A branded type adds a fake, compile-time-only property so they become incompatible.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function toUserId(raw: string): UserId {
if (!raw.startsWith("usr_")) throw new Error("Not a user id");
return raw as UserId; // the one place a cast is allowed: right after validation
}
function getOrders(userId: UserId) { /* ... */ }
const orderId = "ord_123" as OrderId;
getOrders(orderId);
// Error: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'.The only way to get a UserId is through toUserId, so every UserId in the codebase has been validated. The same trick works for EmailAddress, Cents, or SanitizedHtml.
Combine this with the habits from earlier lessons:
- Exhaustive switches with a
nevercheck, so adding a union member breaks the build everywhere it is not handled. noUncheckedIndexedAccess, socoupons[code]above is typedCoupon | undefinedand you are forced to handle a missing key (which the code does).- No
any: turn on the@typescript-eslint/no-explicit-anylint rule, and useunknownplus narrowing instead.
Match each code smell to its fix.
Where types live in a project
In a real app, types are not in one giant types.ts. They sit next to what they describe, and shared contracts get their own place.
- src/
- lib/
- schemas/Zod schemas: the source of truth for external data
- user.tsUserSchema + type User = z.infer<...>
- order.ts
- api/
- users.tsfetch + UserSchema.parse at the edge
- result.tsResult<T, E> type and helpers
- ids.tsbranded types: UserId, OrderId
- components/
- UserCard.tsxprops type declared in the same file
- types/
- env.d.tsglobal declarations (env vars, window)
- assets.d.tsdeclare module "*.svg"
- tsconfig.jsonstrict, noUncheckedIndexedAccess
The rules of thumb: co-locate types with the code that uses them (a component's props live in its file), put domain schemas in one shared folder, and keep .d.ts files for things that are not TypeScript.
as casts is the most reasonable?Parse with a Result type
Instead of throwing, return a Result: a discriminated union that forces the caller to handle failure.
type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };
function parseAge(input: string): Result<number>Rules, checked in this order on the trimmed input:
- Empty →
{ ok: false, error: "empty" } - Not made only of digits 0–9 →
{ ok: false, error: "not a number" }(so"-3","4.5","12a"fail here) - Above 150 →
{ ok: false, error: "out of range" } - Otherwise →
{ ok: true, value: <the number> }
parseAge(" 36 ") → { ok: true, value: 36 }
parseAge("abc") → { ok: false, error: "not a number" }A tiny Zod
Build a miniature version of Zod: schemas that validate unknown data at runtime and carry a static type.
type Schema<T> = {
parse(value: unknown): T; // returns the data or throws an Error
safeParse(value: unknown): { success: true; data: T } | { success: false; error: string };
};Implement z.string(), z.number(), z.boolean() and z.object(shape):
z.number()rejectsNaNand anything that is not a number ("5"fails).z.object({...})requires a non-null, non-array object, checks every field with its schema, and returns a new object with only the known keys (unknown keys are stripped, like Zod).- Error messages include the path to the bad field, for example
address.city: expected string.
const User = z.object({ name: z.string(), age: z.number() });
User.parse({ name: "Ada", age: 36, extra: 1 }); // { name: "Ada", age: 36 }
User.safeParse({ name: "Ada" }); // { success: false, error: "age: expected number" }- trust boundary
- Where data enters your program from outside. Validate there, so everything inside can trust its types.
- type assertion (as)
- Tells the compiler to treat a value as a type without checking it. No runtime effect, so it can hide bugs.
- schema validation
- Checking unknown data against a runtime schema (like Zod) and inferring the static type from it.
- Result type
- A union like
{ ok: true; value } | { ok: false; error }that makes expected failures visible in the type. - branded type
- A primitive intersected with a fake tag, like
string & { __brand: "UserId" }, so similar values cannot be mixed up.