The TypeScript and Node Picture Book
app.tscode + types tsctype checker✘ catches bugs app.jstypes erased Node / browser Types exist only at compile time they never slow your program and vanish from the output they're a spell-checker for your logic, plus autocomplete and safe refactoring
PLATE 0 — JavaScript with a seatbelt. Mistakes show up in your editor, not in production.
A picture book for grown-ups · with code

TypeScript and Node.js

Nine spreads: the type system, functions and objects, generics, narrowing, modules, and then building a typed Node API with validation and tests.

Say it like a pro

"Strict mode, types derived from validated schemas, discriminated unions for state, and no any at the boundaries."

Use the tabs or the ← → keys.

string number boolean bigint string[] Array [string, number] tuple null · undefined Three special types anyswitches checking off. Avoid. unknown"could be anything": check before use never"can't happen": exhaustive checks inference: let n = 5 is already number. Annotate where it can't infer.
PLATE 1 — Let the compiler infer what it can. Write types where it matters: function edges.
Chapter 1 · Setup & basic types

Zero to a compiled file

$ mkdir ts-demo && cd ts-demo && npm init -y
$ npm i -D typescript tsx @types/node
$ npx tsc --init                       # creates tsconfig.json
$ npx tsx src/index.ts                 # run TS directly (dev)
$ npx tsc --noEmit                     # type-check only (CI)
tsconfig.json: turn on the safety
{
  "compilerOptions": {
    "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext",
    "outDir": "dist", "rootDir": "src",
    "strict": true,                       // the one switch that matters
    "noUncheckedIndexedAccess": true,     // arr[i] may be undefined
    "noImplicitOverride": true,
    "esModuleInterop": true, "skipLibCheck": true, "sourceMap": true
  },
  "include": ["src"]
}
let name: string = "Ama";
let age = 31;                           // inferred: number
const tags: string[] = ["a", "b"];
const pair: [string, number] = ["x", 1];
let id: string | number = "u_42";       // union
function parse(input: unknown): number {
  if (typeof input === "string") return Number(input);   // narrowing
  throw new Error("not a string");
}
Say it like a pro

"strict: true from day one, unknown instead of any, and let inference do the rest."

interface User readonly id: string name: string email?: string role: "admin" | "user" extends interface Admin …everything in User permissions: string[] Structural typing ("duck typing", checked) if an object has the right fields, it fits. No "implements" ceremony. type vs interface interface: object shapes, extendable · type: unions, tuples, mapped types, aliases pick one style per codebase; both work for objects excess property checks catch typos in object literals
PLATE 2 — Describe the shape of your data once, and use it everywhere.
Chapter 2 · Objects, interfaces & unions

Shapes, optional fields, and "one of these"

interface User {
  readonly id: string;
  name: string;
  email?: string;                        // optional: string | undefined
  role: "admin" | "user";                // literal union
}
type Admin = User & { permissions: string[] };      // intersection

const u: User = { id: "u1", name: "Ama", role: "user" };
// u.id = "x";                            // ✘ readonly
// const bad: User = { id: "u1", nme: "Ama", role: "user" };   // ✘ typo caught

type Status = "idle" | "loading" | "error";           // union of literals
type Id = string | number;
type Point = { x: number; y: number };
type Keys = keyof Point;                              // "x" | "y"

const config = { port: 3000, host: "localhost" } as const;   // readonly literals
type Config = typeof config;                                  // derive a type from a value

// enum-free alternative:
const Roles = ["admin", "user"] as const;
type Role = (typeof Roles)[number];                   // "admin" | "user"
?.
optional chaining: user?.email?.length
??
nullish default: port ?? 3000 (keeps 0 and "")
satisfies
check a value matches a type without widening it
Say it like a pro

"Literal unions instead of enums, as const to derive types from data, and shapes defined once."

number[] first<T>T = number number same function, any type, type-safe: the type is a parameter Utility types: transform types without rewriting them Partial<User> all fields optional (update payloads) Required<T> · Readonly<T> · Pick<User,"id"|"name"> · Omit<User,"email"> Record<string, number> · ReturnType<typeof fn> · Awaited<Promise<T>> Mapped and conditional types type Nullable<T> = { [K in keyof T]: T[K] | null } type ElementOf<T> = T extends (infer E)[] ? E : never
PLATE 3 — Generics let one definition work across many types without losing safety.
Chapter 3 · Functions & generics

Write it once for every type

function add(a: number, b: number): number { return a + b; }
const greet = (name: string, greeting = "Hello"): string => `${greeting}, ${name}`;
function log(msg: string, ...tags: string[]): void {}

function first<T>(xs: T[]): T | undefined { return xs[0]; }
first([1, 2, 3]);          // number | undefined
first(["a", "b"]);         // string | undefined

// constrain what T can be
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map(i => i[key]);
}
pluck([{ id: 1, name: "a" }], "name");     // string[]   · pluck(…, "oops") is a compile error

// a typed result instead of throwing
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
function parseIntSafe(s: string): Result<number> {
  const n = Number.parseInt(s, 10);
  return Number.isNaN(n) ? { ok: false, error: new Error("NaN") } : { ok: true, value: n };
}

type UpdateUser = Partial<Omit<User, "id">>;      // everything but id, all optional
overloads
several call signatures for one function
don't over-engineer
if a generic needs a paragraph of explanation, simplify it
Say it like a pro

"A generic with a keyof constraint keeps the return type exact with no casts."

type Shape ={kind:"circle", r} | {kind:"square", side} | {kind:"rect", w, h} case "circle" case "square" case "rect" default: const _x: never = s ← add a kind and this line fails to compile Narrowing tools typeof x === "string" · x instanceof Date · "key" in obj · Array.isArray(x) equality / truthiness checks · custom type guards (x is User) inside the check, the compiler knows the narrower type
PLATE 4 — Model states as a union with a tag. The compiler makes you handle every one.
Chapter 4 · Narrowing & discriminated unions

Make illegal states unrepresentable

type Shape =
  | { kind: "circle"; r: number }
  | { kind: "square"; side: number }
  | { kind: "rect"; w: number; h: number };

function area(s: Shape): number {
  switch (s.kind) {
    case "circle": return Math.PI * s.r ** 2;
    case "square": return s.side ** 2;
    case "rect":   return s.w * s.h;
    default: { const _exhaustive: never = s; return _exhaustive; }
  }
}

// async state that can't be half-loaded
type Load<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "ok"; data: T }
  | { status: "error"; message: string };

// custom type guard
function isUser(x: unknown): x is User {
  return typeof x === "object" && x !== null && "id" in x && "name" in x;
}

function len(x: string | string[]) {
  return Array.isArray(x) ? x.length : x.trim().length;   // narrowed in each branch
}
avoid
casting with as to silence errors; it's a promise you must keep
!
non-null assertion: same risk; prefer a check
Say it like a pro

"A tagged union plus an exhaustive switch means a new state can't be forgotten."

user.tsexport type User repo.tsexport class Repo main.tsimports both Class with the right amount of OOP interface Store { get(id): User | undefined; add(u: User): void } class MemoryStore implements Store { #users = new Map() … } Why program to an interface swap the real database for a fake in tests · no rewrites Module rules one concern per file · named exports · no circular imports import type {…} for type-only imports (erased at build)
PLATE 5 — Small modules with explicit exports, depending on interfaces, not implementations.
Chapter 5 · Modules, classes & interfaces

Organize code so it can change

// src/types.ts
export interface User { id: string; name: string }
export interface UserStore {
  get(id: string): Promise<User | undefined>;
  add(u: User): Promise<void>;
}

// src/memoryStore.ts
import type { User, UserStore } from "./types.js";     // NodeNext needs the .js extension
export class MemoryStore implements UserStore {
  #users = new Map<string, User>();                    // truly private (#)
  async get(id: string) { return this.#users.get(id); }
  async add(u: User)    { this.#users.set(u.id, u); }
}

// src/service.ts: depends on the interface
export class UserService {
  constructor(private readonly store: UserStore) {}      // parameter property
  async rename(id: string, name: string) {
    const u = await this.store.get(id);
    if (!u) throw new Error(`user ${id} not found`);
    await this.store.add({ ...u, name });
  }
}
// production: new UserService(new PgStore(pool))   ·   test: new UserService(new MemoryStore())
ESM vs CJS
use "type": "module" in package.json for ESM; match tsconfig module to it
declaration files
@types/express etc. give types to JS libraries
composition
prefer small functions and composition over deep inheritance
Say it like a pro

"Services depend on interfaces, so tests inject in-memory fakes and production injects the real store."

Call stackruns JS, onething at a time libuv + OS timers · I/Odone → callback microtaskspromises, await macrotaskstimers, I/O One thread, many waiting jobs I/O is handed to the OS; the thread stays free to serve other requests a CPU-heavy loop blocks everything → use worker_threads or another service Don't forget await in a loop runs serially · Promise.all runs concurrently always handle rejections · set timeouts · limit concurrency
PLATE 6 — Node never waits. It starts the job, moves on, and comes back when it's done.
Chapter 6 · Async & the Node runtime

Promises, await, and typed I/O

import { readFile } from "node:fs/promises";

async function loadConfig(path: string): Promise<{ port: number }> {
  const raw = await readFile(path, "utf8");
  return JSON.parse(raw) as { port: number };          // ⚠ unchecked: see chapter 7
}

// run independent work concurrently, not one by one
const [user, orders] = await Promise.all([fetchUser(id), fetchOrders(id)]);

// timeout + cancellation (Node 18+)
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 3000);
try {
  const res = await fetch("https://api.example.com/data", { signal: ctrl.signal });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data: unknown = await res.json();              // unknown until validated
} finally { clearTimeout(timer); }

// bounded concurrency without a library
async function mapLimit<T, R>(xs: T[], n: number, fn: (x: T) => Promise<R>): Promise<R[]> {
  const out: R[] = []; let i = 0;
  await Promise.all(Array.from({ length: n }, async () => {
    while (i < xs.length) { const k = i++; out[k] = await fn(xs[k]); }
  }));
  return out;
}
Promise.allSettled
wait for all, keep failures
node:
prefix for built-in modules: node:fs, node:path, node:http
process.on('unhandledRejection')
log and exit; don't let it vanish
Say it like a pro

"Promise.all for independent calls, AbortController for timeouts, and bounded concurrency for bulk work."

outside worldJSON, env, forms unknown schemazod .parse() typed your codetrusted, typed TypeScript can't see runtime data types vanish at runtime: JSON.parse(x) as User checks nothing Fix: one schema, two jobs validate at every boundary: HTTP bodies, query strings, env vars, files, API responses infer the static type from the schema (z.infer), so they can't drift alternatives: valibot · ArkType · typebox · io-ts return a 400 with the issues, not a crash
PLATE 7 — Types check your code. Schemas check the world.
Chapter 7 · Validation at the boundary

Trust nothing that arrives from outside

$ npm i zod
import { z } from "zod";

export const CreateTask = z.object({
  title: z.string().trim().min(1).max(200),
  due:   z.coerce.date().optional(),
  tags:  z.array(z.string()).max(10).default([]),
}).strict();
export type CreateTask = z.infer<typeof CreateTask>;     // type derived from the schema

const parsed = CreateTask.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ issues: parsed.error.issues });
const task: CreateTask = parsed.data;                    // now it's trustworthy

// env vars, validated once at startup
const Env = z.object({
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  JWT_SECRET: z.string().min(32),
});
export const env = Env.parse(process.env);               // crash early with a clear message
refine / transform
custom rules and reshaping while parsing
branded types
type UserId = string & { __brand: "UserId" } prevents mixing up IDs
Say it like a pro

"Zod at every boundary, with types inferred from the schemas and the environment validated at startup."

Client validatezod handlertyped service store Project scripts that keep it honest "dev": tsx watch src/server.ts · "build": tsc · "start": node dist/server.js "typecheck": tsc --noEmit · "lint": eslint . · "test": vitest run Share types with the frontend export the zod schemas / inferred types from a shared package or generate a typed client from OpenAPI, or use tRPC for end-to-end types CI gate typecheck → lint → test → build must all pass
PLATE 8 — Types from the request all the way to the database.
Chapter 8 · Build a typed API

Express + zod + TypeScript

$ npm i express zod && npm i -D @types/express vitest supertest @types/supertest
// src/app.ts
import express, { type Request, type Response, type NextFunction } from "express";
import { z } from "zod";

const app = express();
app.use(express.json({ limit: "100kb" }));

const validate = <S extends z.ZodTypeAny>(schema: S) =>
  (req: Request, res: Response, next: NextFunction) => {
    const r = schema.safeParse(req.body);
    if (!r.success) return res.status(400).json({ error: "validation", issues: r.error.issues });
    req.body = r.data; next();
  };

const NewTask = z.object({ title: z.string().min(1).max(200) }).strict();
type Task = { id: number; title: string; done: boolean };
const tasks: Task[] = [];                                       // swap for a real store

app.post("/tasks", validate(NewTask), (req, res) => {
  const t: Task = { id: tasks.length + 1, title: req.body.title, done: false };
  tasks.push(t); res.status(201).json(t);
});
app.get("/tasks", (_req, res) => res.json(tasks));

app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {   // one error handler
  console.error(err); res.status(500).json({ error: "internal" });
});
export default app;

// test/tasks.test.ts
import request from "supertest"; import { test, expect } from "vitest"; import app from "../src/app.js";
test("rejects an empty title", async () => {
  const r = await request(app).post("/tasks").send({ title: "" });
  expect(r.status).toBe(400);
});
Say it like a pro

"Schemas generate the types, handlers are typed, one error handler, and CI runs typecheck, lint, test and build."

editor tsc/tsx ESLint Vitest Skill ladder 1 basics + strict 2 unions + narrowing 3 generics + utility types 4 schemas at boundaries 5 mapped / conditional types stop at the level where types still make the code simpler
PLATE 9 — Most of the benefit comes from the first few rungs.
Chapter 9 · Tooling & next steps

Lint, format, test, and keep learning

$ npm i -D eslint typescript-eslint prettier
$ npx eslint . ; npx prettier --write .
$ npx tsc --noEmit --watch                # live type-check while you code
$ npx tsc --listFiles | head ; npx tsc --showConfig
// eslint.config.js (flat config)
import tseslint from "typescript-eslint";
export default tseslint.config(...tseslint.configs.recommendedTypeChecked, {
  languageOptions: { parserOptions: { projectService: true } },
  rules: { "@typescript-eslint/no-floating-promises": "error", "@typescript-eslint/no-explicit-any": "error" },
});
  1. Migrate JS gradually: allowJs + checkJs, rename files one at a time, tighten flags as you go.
  2. Prefer inference for locals and explicit types for public function signatures.
  3. Ban the escape hatches: lint against any, unchecked as, and floating promises.
  4. Read errors from the bottom up: the last line of a long TS error usually names the real mismatch.
practise
Type Challenges · the official TypeScript Handbook · Matt Pocock's Total TypeScript
next
Next.js or React with TS · Prisma/Drizzle (typed DB access) · tRPC · monorepos with project references
Say it like a pro

"Strict TS, type-aware lint rules, validated boundaries, and a CI gate. That catches most bugs before they ship."