Skip to content

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.

18 min read0/4 questions

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:

Validate at the edge, trust inside
External API: any shapeExternal APIany shapeForm / URL: stringsForm / URLstringsValidate: unknown → UserValidateunknown → UserApp logic: typed, trustedApp logictyped, trustedError path: 400 / messageError path400 / messageunknownunknownUserinvalid

Everything from outside enters as unknown. That forces a check before use.

1/3

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 nothing

An 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.

Predict the outputTypeScript

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}`);
Need a nudge? Hints walk you through it.

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).

src/lib/schemas/user.ts
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 }
src/lib/api/users.ts
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:

TypeScript
type Schema<T> = (value: unknown, path?: string) => T; const str: Schema<string> = (v, path = "value") => { if (typeof v !== "string") throw new Error(`${path}: expected string`); return v;}; const num: Schema<number> = (v, path = "value") => { if (typeof v !== "number" || Number.isNaN(v)) throw new Error(`${path}: expected number`); return v;}; function parseProduct(v: unknown) { if (typeof v !== "object" || v === null) throw new Error("expected object"); const o = v as Record<string, unknown>; return { name: str(o.name, "name"), priceCents: num(o.priceCents, "priceCents") };} for (const json of ['{"name":"Lamp","priceCents":1999}', '{"name":"Lamp","price":1999}']) { try { console.log("ok", parseProduct(JSON.parse(json))); } catch (e) { console.log("rejected:", (e as Error).message); }}
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Why use z.infer<typeof UserSchema> instead of writing a User type by hand?
Need a nudge? A hint rules out a wrong answer.

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.

TypeScript
type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E }; type Coupon = { code: string; percentOff: number }; function applyCoupon(totalCents: number, coupon: Coupon | undefined): Result<number> { if (!coupon) return { ok: false, error: "Unknown coupon" }; if (coupon.percentOff <= 0 || coupon.percentOff > 90) return { ok: false, error: "Invalid discount" }; return { ok: true, value: Math.round(totalCents * (1 - coupon.percentOff / 100)) };} const coupons: Record<string, Coupon> = { SAVE10: { code: "SAVE10", percentOff: 10 } }; for (const code of ["SAVE10", "FREE"]) { const r = applyCoupon(5000, coupons[code]); console.log(r.ok ? `Pay ${r.value}` : `Error: ${r.error}`);}
Output
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 never check, so adding a union member breaks the build everywhere it is not handled.
  • noUncheckedIndexedAccess, so coupons[code] above is typed Coupon | undefined and you are forced to handle a missing key (which the code does).
  • No any: turn on the @typescript-eslint/no-explicit-any lint rule, and use unknown plus narrowing instead.
Match the pairs0/5 matched

Match each code smell to its fix.

Choose an item, then its match on the other side.

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.

Types in a typical Next.js or Vite app
  • 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.

Quick check
Which of these as casts is the most reasonable?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

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:

  1. Empty → { ok: false, error: "empty" }
  2. Not made only of digits 0–9 → { ok: false, error: "not a number" } (so "-3", "4.5", "12a" fail here)
  3. Above 150 → { ok: false, error: "out of range" }
  4. Otherwise → { ok: true, value: <the number> }
parseAge(" 36 ")  →  { ok: true, value: 36 }
parseAge("abc")   →  { ok: false, error: "not a number" }
TypeScript
type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E }; function parseAge(input: string): Result<number> { return { ok: false, error: "empty" };}
ChallengeHard

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() rejects NaN and 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" }
TypeScript
type Schema<T> = { parse(value: unknown): T; safeParse( value: unknown, ): { success: true; data: T } | { success: false; error: string };}; const z = { string(): Schema<string> { throw new Error("Not implemented"); }, number(): Schema<number> { throw new Error("Not implemented"); }, boolean(): Schema<boolean> { throw new Error("Not implemented"); }, object<S extends Record<string, Schema<unknown>>>( shape: S, ): Schema<{ [K in keyof S]: S[K] extends Schema<infer T> ? T : never }> { throw new Error("Not implemented"); },};
Key terms
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.