Nine spreads: the type system, functions and objects, generics, narrowing, modules, and then building a typed Node API with validation and tests.
"Strict mode, types derived from validated schemas, discriminated unions for state, and no any at the boundaries."
Use the tabs or the ← → keys.
$ 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)
{
"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");
}
"strict: true from day one, unknown instead of any, and let inference do the rest."
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"
user?.email?.lengthport ?? 3000 (keeps 0 and "")"Literal unions instead of enums, as const to derive types from data, and shapes defined once."
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
"A generic with a keyof constraint keeps the return type exact with no casts."
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
}
as to silence errors; it's a promise you must keep"A tagged union plus an exhaustive switch means a new state can't be forgotten."
// 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())
"type": "module" in package.json for ESM; match tsconfig module to it@types/express etc. give types to JS libraries"Services depend on interfaces, so tests inject in-memory fakes and production injects the real store."
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;
}
node:fs, node:path, node:http"Promise.all for independent calls, AbortController for timeouts, and bounded concurrency for bulk work."
$ 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
type UserId = string & { __brand: "UserId" } prevents mixing up IDs"Zod at every boundary, with types inferred from the schemas and the environment validated at startup."
$ 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);
});
"Schemas generate the types, handlers are typed, one error handler, and CI runs typecheck, lint, test and build."
$ 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" },
});
allowJs + checkJs, rename files one at a time, tighten flags as you go.any, unchecked as, and floating promises."Strict TS, type-aware lint rules, validated boundaries, and a CI gate. That catches most bugs before they ship."