{"id":"6b0941815ce40d447918f2fd","slug":"typescript","title":"TypeScript for React and Node developers – from types to a type-safe API","summary":"A hands-on TypeScript 7 guide built around one project – a dumpling shop's order dashboard in React plus a Node script. Types vs interfaces, discriminated unions, narrowing, generics, utility types, a strict tsconfig and validating API responses with Zod.","servedLang":"en","availableLangs":["pl","en"],"topics":["typescript","react"],"techs":["typescript","node","javascript"],"tags":["typescript-7","react-19","zod","generics","discriminated-unions","utility-types","tsconfig","vite","node-24"],"level":"intermediate","kind":"tutorial","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":26,"stats":{"views":6,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:25.168Z","updatedAt":"2026-11-27T13:02:47.273Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"TypeScript 7 in practice for React and Node.js – type vs interface, generics, narrowing, discriminated unions, utility types, strict tsconfig, Zod for typing API responses, running .ts files in Node 24 and common pitfalls.","wordCount":5179,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"TypeScript isn't there to make the compiler stop complaining. Its job is to make invalid application states impossible to write down in the first place. In this guide you'll build a small but complete project: an order dashboard for a dumpling shop in React, plus a Node script that checks the data coming from the API. Along the way you'll cover everything you use day to day – from choosing between "},{"type":"text","text":"type","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"interface","marks":[{"type":"code"}]},{"type":"text","text":" to validating JSON from the server."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Model "},{"type":"text","text":"states","marks":[{"type":"bold"}]},{"type":"text","text":", not just fields: a discriminated union ("},{"type":"text","text":"kind: \"cooking\" | \"delivering\" | …","marks":[{"type":"code"}]},{"type":"text","text":") plus an exhaustive "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" means a new order status breaks the build everywhere it needs handling."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Anything from the outside world (API, "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":", forms) is "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" until it passes a schema. "},{"type":"text","text":"Zod","marks":[{"type":"bold"}]},{"type":"text","text":" validates it at runtime, and you derive the type from the schema instead of writing it twice."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"TypeScript 7","marks":[{"type":"bold"}]},{"type":"text","text":" is the native compiler (8–12× faster full builds), and since 6.0 "},{"type":"text","text":"strict","marks":[{"type":"code"}]},{"type":"text","text":" is on by default. Node 24 runs "},{"type":"text","text":".ts","marks":[{"type":"code"}]},{"type":"text","text":" files without a build step, as long as you only use syntax that can simply be erased."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you'll build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"A Vite + React 19 app that fetches orders from "},{"type":"text","text":"/orders.json","marks":[{"type":"code"}]},{"type":"text","text":", validates every record with a Zod schema, maps it from the API format (snake_case, prices in grosze) to a domain model and renders order cards with a status filter. Plus a "},{"type":"text","text":"node scripts/check-orders.ts","marks":[{"type":"code"}]},{"type":"text","text":" script that checks the data file using the very same types and schemas. All the code (21 files) downloads as a ZIP with one click – use the download icon next to the article."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 24 (or 22.18+), JavaScript basics (ES2015+, "},{"type":"text","text":"async/await","marks":[{"type":"code"}]},{"type":"text","text":", modules) and React basics (components, props, "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":"). No prior TypeScript version knowledge required."}]},{"type":"stats","attrs":{"items":[{"value":"7.0","label":"TypeScript version","hint":"native compiler written in Go"},{"value":"8–12×","label":"faster full builds","hint":"according to the TypeScript team"},{"value":"strict","label":"default since 6.0","hint":"no need to switch it on by hand"},{"value":"0","label":"`any` in app code","hint":"`unknown` + a schema instead of guessing"}]}},{"type":"heading","attrs":{"level":2,"id":"step-0-a-project-and-a-tsconfig-that-actually-guards-you"},"content":[{"type":"text","text":"Step 0. A project and a tsconfig that actually guards you"}]},{"type":"paragraph","content":[{"type":"text","text":"Start from the Vite template – it generates two config files: one for browser code and one for files run by Node (the Vite config, scripts)."}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm create vite@latest pierogi-ts -- --template react-ts\ncd pierogi-ts\nnpm install zod\nnpm run dev"}]},{"type":"paragraph","content":[{"type":"text","text":"TypeScript 6.0 was a transition release that flipped several defaults, and 7.0 removed the old options for good. If you're moving an older project, these are the changes that surprise people most:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Option"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Now (6.0/7.0)"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What it means in practice"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"strict","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"true","marks":[{"type":"code"}]},{"type":"text","text":" by default"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"undefined","marks":[{"type":"code"}]},{"type":"text","text":" and implicit "},{"type":"text","text":"any","marks":[{"type":"code"}]},{"type":"text","text":" are errors from day one"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"types","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":" by default"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"global types ("},{"type":"text","text":"process","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"describe","marks":[{"type":"code"}]},{"type":"text","text":") must be listed, e.g. "},{"type":"text","text":"\"types\": [\"node\"]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"module","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"target","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"esnext","marks":[{"type":"code"}]},{"type":"text","text":" / latest ES"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no more ES5 output – the lowest target is ES2015"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"baseUrl","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"moduleResolution: \"node\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"removed in 7.0"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"use "},{"type":"text","text":"bundler","marks":[{"type":"code"}]},{"type":"text","text":" (Vite) or "},{"type":"text","text":"nodenext","marks":[{"type":"code"}]},{"type":"text","text":" (Node) and aliases via "},{"type":"text","text":"paths","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"esModuleInterop: false","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"not allowed"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"default imports from CommonJS packages simply work"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Here's the project configuration. On top of the template settings we added "},{"type":"text","text":"noUncheckedIndexedAccess","marks":[{"type":"code"}]},{"type":"text","text":" (indexing an array or record may return "},{"type":"text","text":"undefined","marks":[{"type":"code"}]},{"type":"text","text":") and "},{"type":"text","text":"noImplicitOverride","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"codeGroup","attrs":{"title":"Project configuration"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-ts\",\n  \"private\": true,\n  \"version\": \"0.1.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc -b && vite build\",\n    \"typecheck\": \"tsc -b\",\n    \"check:orders\": \"node scripts/check-orders.ts\"\n  },\n  \"dependencies\": {\n    \"react\": \"^19.3.1\",\n    \"react-dom\": \"^19.3.1\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^24.0.0\",\n    \"@types/react\": \"^19.3.0\",\n    \"@types/react-dom\": \"^19.3.0\",\n    \"@vitejs/plugin-react\": \"^6.3.0\",\n    \"typescript\": \"~7.0.2\",\n    \"vite\": \"^8.4.0\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"files\": [],\n  \"references\": [{ \"path\": \"./tsconfig.app.json\" }, { \"path\": \"./tsconfig.node.json\" }]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.app.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.app.tsbuildinfo\",\n    \"target\": \"es2023\",\n    \"lib\": [\"ES2023\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"bundler\",\n    \"types\": [\"vite/client\"],\n    \"jsx\": \"react-jsx\",\n    \"noEmit\": true,\n    \"allowImportingTsExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"erasableSyntaxOnly\": true,\n    \"moduleDetection\": \"force\",\n    \"skipLibCheck\": true,\n\n    \"noUncheckedIndexedAccess\": true,\n    \"noImplicitOverride\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true\n  },\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.node.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \"./node_modules/.tmp/tsconfig.node.tsbuildinfo\",\n    \"target\": \"es2023\",\n    \"lib\": [\"ES2023\"],\n    \"module\": \"nodenext\",\n    \"types\": [\"node\"],\n    \"noEmit\": true,\n    \"allowImportingTsExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"erasableSyntaxOnly\": true,\n    \"skipLibCheck\": true,\n    \"noUncheckedIndexedAccess\": true\n  },\n  \"include\": [\"vite.config.ts\", \"scripts\", \"examples\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"vite.config.ts"},"content":[{"type":"text","text":"import react from \"@vitejs/plugin-react\";\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  plugins: [react()],\n});"}]},{"type":"codeBlock","attrs":{"language":"html","filename":"index.html"},"content":[{"type":"text","text":"<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Pierogi TS</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>"}]}]},{"type":"paragraph","content":[{"type":"text","text":"A few flags deserve a closer look:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"verbatimModuleSyntax","marks":[{"type":"code"}]},{"type":"text","text":" – imports used only as types must say "},{"type":"text","text":"import type","marks":[{"type":"code"}]},{"type":"text","text":". Tools that just erase types (Vite, Node) then don't have to guess what to drop."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"erasableSyntaxOnly","marks":[{"type":"code"}]},{"type":"text","text":" – forbids constructs that emit runtime code: "},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":", value "},{"type":"text","text":"namespace","marks":[{"type":"code"}]},{"type":"text","text":"s and constructor parameter properties ("},{"type":"text","text":"constructor(private x: number)","marks":[{"type":"code"}]},{"type":"text","text":"). Use literal unions instead of "},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"allowImportingTsExtensions","marks":[{"type":"code"}]},{"type":"text","text":" – you import "},{"type":"text","text":"./App.tsx","marks":[{"type":"code"}]},{"type":"text","text":", not "},{"type":"text","text":"./App","marks":[{"type":"code"}]},{"type":"text","text":". Vite and Node both understand imports written that way."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"noUncheckedIndexedAccess","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"orders[0]","marks":[{"type":"code"}]},{"type":"text","text":" is "},{"type":"text","text":"Order | undefined","marks":[{"type":"code"}]},{"type":"text","text":". Annoying at first, but it catches real bugs with empty lists."}]}]}]},{"type":"callout","attrs":{"variant":"warning","title":"\"Cannot find name 'process'\" after upgrading"},"content":[{"type":"paragraph","content":[{"type":"text","text":"That's the new "},{"type":"text","text":"\"types\": []","marks":[{"type":"code"}]},{"type":"text","text":" default. The compiler no longer loads every "},{"type":"text","text":"@types/*","marks":[{"type":"code"}]},{"type":"text","text":" package automatically. Add what you need to "},{"type":"text","text":"types","marks":[{"type":"code"}]},{"type":"text","text":" in the right config: "},{"type":"text","text":"[\"node\"]","marks":[{"type":"code"}]},{"type":"text","text":" for scripts, "},{"type":"text","text":"[\"vite/client\"]","marks":[{"type":"code"}]},{"type":"text","text":" for the app, "},{"type":"text","text":"[\"vitest/globals\"]","marks":[{"type":"code"}]},{"type":"text","text":" for tests."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-1-types-or-interfaces"},"content":[{"type":"text","text":"Step 1. Types or interfaces?"}]},{"type":"paragraph","content":[{"type":"text","text":"It's the most common question, and the good news is that for plain objects both work almost the same. The differences are in the details:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph"}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"interface","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"type","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Object shape"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Unions, tuples, primitives"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes ("},{"type":"text","text":"\"vegan\" | \"spicy\"","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"[number, number]","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Mapped and conditional types"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes ("},{"type":"text","text":"Record<…>","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Pick<…>","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"T extends U ? …","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Extending"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"extends","marks":[{"type":"code"}]},{"type":"text","text":", readable errors"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"&","marks":[{"type":"code"}]},{"type":"text","text":" (intersection), errors can be less readable"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Declaration merging"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes – two declarations with the same name merge"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no – a duplicate is an error"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"A rule that works well in teams: "},{"type":"text","text":"interface","marks":[{"type":"code"}]},{"type":"text","text":" for object shapes that others extend (contracts, props, models), ","marks":[{"type":"bold"}]},{"type":"text","text":"type","marks":[{"type":"code"}]},{"type":"text","text":" for anything that's a union or is computed from other types.","marks":[{"type":"bold"}]},{"type":"text","text":" What matters most is that the team sticks to one convention."}]},{"type":"paragraph","content":[{"type":"text","text":"The dumpling shop's domain model uses both. Note the "},{"type":"text","text":"branded types","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"OrderId","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"MenuItemId","marks":[{"type":"code"}]},{"type":"text","text":" are plain strings at runtime, but the compiler won't let you pass one where the other is expected:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/domain/order.ts"},"content":[{"type":"text","text":"// Type aliases: unions, brands and anything computed from other types.\nexport type Tag = \"vegan\" | \"spicy\" | \"new\";\nexport type Filling = \"potato-cheese\" | \"meat\" | \"cabbage-mushroom\";\n\n// Branded ids: both are strings at runtime, but they cannot be mixed up at compile time.\nexport type OrderId = string & { readonly __brand: \"OrderId\" };\nexport type MenuItemId = string & { readonly __brand: \"MenuItemId\" };\n\n// Interfaces: object shapes that other shapes extend (public contracts).\nexport interface MenuItem {\n  readonly id: MenuItemId;\n  name: string;\n  priceCents: number;\n  tags: readonly Tag[];\n}\n\nexport interface DumplingItem extends MenuItem {\n  filling: Filling;\n  pieces: 6 | 10 | 20;\n}\n\nexport interface OrderLine {\n  itemId: MenuItemId;\n  name: string;\n  quantity: number;\n  unitPriceCents: number;\n}\n\n// Discriminated union: `kind` tells TypeScript which fields exist.\nexport type OrderStatus =\n  | { kind: \"placed\"; placedAt: Date }\n  | { kind: \"cooking\"; etaMinutes: number }\n  | { kind: \"delivering\"; courier: string; etaMinutes: number }\n  | { kind: \"delivered\"; deliveredAt: Date }\n  | { kind: \"cancelled\"; reason: string };\n\nexport type OrderStatusKind = OrderStatus[\"kind\"]; // \"placed\" | \"cooking\" | ...\n\nexport interface Order {\n  id: OrderId;\n  customer: string;\n  lines: OrderLine[];\n  status: OrderStatus;\n  note?: string;\n}\n\n// The only place where a raw string becomes a branded id.\nexport const toOrderId = (raw: string): OrderId => raw as OrderId;\nexport const toMenuItemId = (raw: string): MenuItemId => raw as MenuItemId;"}]},{"type":"paragraph","content":[{"type":"text","text":"The "},{"type":"text","text":"__brand","marks":[{"type":"code"}]},{"type":"text","text":" marker exists only in the type system. The only place where a plain string becomes an "},{"type":"text","text":"OrderId","marks":[{"type":"code"}]},{"type":"text","text":" is "},{"type":"text","text":"toOrderId","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"toMenuItemId","marks":[{"type":"code"}]},{"type":"text","text":". You call them in the layer that validates API data and nowhere else."}]},{"type":"heading","attrs":{"level":2,"id":"step-2-discriminated-unions-and-an-exhaustive-switch"},"content":[{"type":"text","text":"Step 2. Discriminated unions and an exhaustive switch"}]},{"type":"paragraph","content":[{"type":"text","text":"The classic modelling mistake is one object with optional fields: "},{"type":"text","text":"status: string; courier?: string; etaMinutes?: number; reason?: string","marks":[{"type":"code"}]},{"type":"text","text":". That type happily accepts an order that is \"cancelled, with a courier on the way and no cancellation reason\". A "},{"type":"text","text":"discriminated union","marks":[{"type":"bold"}]},{"type":"text","text":" describes each state separately, and the shared "},{"type":"text","text":"kind","marks":[{"type":"code"}]},{"type":"text","text":" field tells the compiler which variant you're handling."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"stateDiagram-v2\n  [*] --> placed: placedAt\n  placed --> cooking: etaMinutes\n  cooking --> delivering: courier, etaMinutes\n  delivering --> delivered: deliveredAt\n  placed --> cancelled: reason\n  cooking --> cancelled: reason\n  delivered --> [*]\n  cancelled --> [*]","caption":"An order as a state machine – each state carries only its own fields"}},{"type":"paragraph","content":[{"type":"text","text":"Inside "},{"type":"text","text":"case \"delivering\"","marks":[{"type":"code"}]},{"type":"text","text":" TypeScript knows "},{"type":"text","text":"status.courier","marks":[{"type":"code"}]},{"type":"text","text":" exists. In the "},{"type":"text","text":"default","marks":[{"type":"code"}]},{"type":"text","text":" branch the type left over is "},{"type":"text","text":"never","marks":[{"type":"code"}]},{"type":"text","text":". If someone adds a "},{"type":"text","text":"\"refunded\"","marks":[{"type":"code"}]},{"type":"text","text":" status and forgets to handle it, the "},{"type":"text","text":"assertNever(status)","marks":[{"type":"code"}]},{"type":"text","text":" call stops compiling:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/domain/status.ts"},"content":[{"type":"text","text":"import type { Order, OrderStatus } from \"./order.ts\";\n\nexport function assertNever(value: never): never {\n  throw new Error(`Unhandled value: ${JSON.stringify(value)}`);\n}\n\n// Exhaustive switch: add a new status kind and this function stops compiling.\nexport function describeStatus(status: OrderStatus): string {\n  switch (status.kind) {\n    case \"placed\":\n      return `Placed at ${status.placedAt.toLocaleTimeString()}`;\n    case \"cooking\":\n      return `In the kitchen, ready in ~${status.etaMinutes} min`;\n    case \"delivering\":\n      return `${status.courier} is on the way (${status.etaMinutes} min)`;\n    case \"delivered\":\n      return `Delivered at ${status.deliveredAt.toLocaleTimeString()}`;\n    case \"cancelled\":\n      return `Cancelled: ${status.reason}`;\n    default:\n      return assertNever(status);\n  }\n}\n\n// Extract<> picks union members by their discriminant.\nexport type ActiveStatus = Extract<OrderStatus, { kind: \"cooking\" | \"delivering\" }>;\n\n// Type predicate: after `if (isActive(o.status))` the status is ActiveStatus.\nexport function isActive(status: OrderStatus): status is ActiveStatus {\n  return status.kind === \"cooking\" || status.kind === \"delivering\";\n}\n\nexport function totalCents(order: Pick<Order, \"lines\">): number {\n  return order.lines.reduce((sum, line) => sum + line.quantity * line.unitPriceCents, 0);\n}"}]},{"type":"paragraph","content":[{"type":"text","text":"isActive","marks":[{"type":"code"}]},{"type":"text","text":" is a "},{"type":"text","text":"type predicate","marks":[{"type":"bold"}]},{"type":"text","text":": it returns a "},{"type":"text","text":"boolean","marks":[{"type":"code"}]},{"type":"text","text":", but the "},{"type":"text","text":"status is ActiveStatus","marks":[{"type":"code"}]},{"type":"text","text":" signature tells the compiler how to narrow after the check. "},{"type":"text","text":"Extract<OrderStatus, { kind: … }>","marks":[{"type":"code"}]},{"type":"text","text":" picks the matching union members, so you don't retype them."}]},{"type":"heading","attrs":{"level":2,"id":"step-3-narrowing"},"content":[{"type":"text","text":"Step 3. Narrowing"}]},{"type":"paragraph","content":[{"type":"text","text":"Narrowing is how the compiler follows your "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":"s. You have several tools:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"typeof x === \"string\"","marks":[{"type":"code"}]},{"type":"text","text":" – primitives,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"x instanceof Error","marks":[{"type":"code"}]},{"type":"text","text":" – classes,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"\"message\" in x","marks":[{"type":"code"}]},{"type":"text","text":" – property presence (also works on "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" after "},{"type":"text","text":"typeof x === \"object\" && x !== null","marks":[{"type":"code"}]},{"type":"text","text":"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"comparing with a literal ("},{"type":"text","text":"status.kind === \"cooking\"","marks":[{"type":"code"}]},{"type":"text","text":") – discriminated unions,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"predicates "},{"type":"text","text":"x is T","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"assertion functions","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"asserts x is T","marks":[{"type":"code"}]},{"type":"text","text":" – your own narrowing rules,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"the "},{"type":"text","text":"satisfies","marks":[{"type":"code"}]},{"type":"text","text":" operator – checks a value against a type "},{"type":"text","text":"without widening","marks":[{"type":"bold"}]},{"type":"text","text":" it."}]}]}]},{"type":"codeGroup","attrs":{"title":"Type guards and satisfies"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/lib/guards.ts"},"content":[{"type":"text","text":"// typeof, instanceof and `in` narrow `unknown` step by step – no casts needed.\nexport function errorMessage(error: unknown): string {\n  if (error instanceof Error) return error.message;\n  if (typeof error === \"string\") return error;\n  if (typeof error === \"object\" && error !== null && \"message\" in error && typeof error.message === \"string\") {\n    return error.message;\n  }\n  return \"Unknown error\";\n}\n\n// Assertion function: after the call TypeScript knows the value is not null/undefined.\nexport function assertDefined<T>(value: T, name: string): asserts value is NonNullable<T> {\n  if (value === undefined || value === null) throw new Error(`${name} is missing`);\n}\n\n// Union parameter narrowed with typeof.\nexport function formatPrice(amount: number | string, currency = \"PLN\"): string {\n  const cents = typeof amount === \"string\" ? Math.round(Number.parseFloat(amount) * 100) : amount;\n  return new Intl.NumberFormat(\"pl-PL\", { style: \"currency\", currency }).format(cents / 100);\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/components/statusColors.ts"},"content":[{"type":"text","text":"import type { OrderStatusKind } from \"../domain/order.ts\";\n\n// `satisfies` checks the shape (every kind has a colour) but keeps the literal types.\nexport const statusColors = {\n  placed: \"#1c7ed6\",\n  cooking: \"#e8590c\",\n  delivering: \"#7048e8\",\n  delivered: \"#2b8a3e\",\n  cancelled: \"#868e96\",\n} satisfies Record<OrderStatusKind, string>;"}]}]},{"type":"paragraph","content":[{"type":"text","text":"errorMessage(error: unknown)","marks":[{"type":"code"}]},{"type":"text","text":" is the template for every "},{"type":"text","text":"catch","marks":[{"type":"code"}]},{"type":"text","text":" block. In JavaScript you can throw anything, not just an "},{"type":"text","text":"Error","marks":[{"type":"code"}]},{"type":"text","text":", so "},{"type":"text","text":"catch (e)","marks":[{"type":"code"}]},{"type":"text","text":" gives you "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" and you have to narrow it. "},{"type":"text","text":"assertDefined","marks":[{"type":"code"}]},{"type":"text","text":" replaces the "},{"type":"text","text":"!","marks":[{"type":"code"}]},{"type":"text","text":" operator – instead of a silent \"surely not null\" assumption you get a clear exception right where the problem is. "},{"type":"text","text":"satisfies Record<OrderStatusKind, string>","marks":[{"type":"code"}]},{"type":"text","text":" guarantees every status has a colour. A typo like "},{"type":"text","text":"\"canceled\"","marks":[{"type":"code"}]},{"type":"text","text":" in the map is flagged, while the object's type stays precise."}]},{"type":"heading","attrs":{"level":2,"id":"step-4-generics-without-fear"},"content":[{"type":"text","text":"Step 4. Generics without fear"}]},{"type":"paragraph","content":[{"type":"text","text":"A generic is a type parameter: a function or component works for many types without losing track of which one was used. When you call a generic function you almost never write the type in angle brackets – the compiler infers it from the arguments."}]},{"type":"codeGroup","attrs":{"title":"Result, groupBy and a generic component"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/lib/result.ts"},"content":[{"type":"text","text":"// A generic Result: errors become part of the return type instead of hidden exceptions.\nexport type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\nexport const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });\nexport const err = <E>(error: E): Result<never, E> => ({ ok: false, error });\n\n// K extends PropertyKey: the key function must return something usable as an object key.\nexport function groupBy<T, K extends PropertyKey>(items: readonly T[], keyOf: (item: T) => K): Partial<Record<K, T[]>> {\n  const groups: Partial<Record<K, T[]>> = {};\n  for (const item of items) {\n    (groups[keyOf(item)] ??= []).push(item);\n  }\n  return groups;\n}\n\n// K extends keyof T: only existing property names are accepted, and the result type follows.\nexport function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {\n  return items.map((item) => item[key]);\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/components/Select.tsx"},"content":[{"type":"text","text":"// Generic component: T is inferred from `value` and `options` at the call site.\ninterface SelectProps<T extends string> {\n  label: string;\n  value: T;\n  options: readonly { value: T; label: string }[];\n  onChange: (value: T) => void;\n}\n\nexport function Select<T extends string>({ label, value, options, onChange }: SelectProps<T>) {\n  return (\n    <label style={{ display: \"inline-flex\", gap: 8, alignItems: \"center\" }}>\n      {label}\n      <select\n        value={value}\n        onChange={(e) => {\n          // Narrow the DOM string back to T instead of casting with `as T`.\n          const next = options.find((o) => o.value === e.target.value);\n          if (next) onChange(next.value);\n        }}\n      >\n        {options.map((o) => (\n          <option key={o.value} value={o.value}>\n            {o.label}\n          </option>\n        ))}\n      </select>\n    </label>\n  );\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Things to notice:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Constraints","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"K extends PropertyKey","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"K extends keyof T","marks":[{"type":"code"}]},{"type":"text","text":" say what you require from the parameter. So "},{"type":"text","text":"pluck(orders, \"customer\")","marks":[{"type":"code"}]},{"type":"text","text":" returns "},{"type":"text","text":"string[]","marks":[{"type":"code"}]},{"type":"text","text":", and "},{"type":"text","text":"pluck(orders, \"costomer\")","marks":[{"type":"code"}]},{"type":"text","text":" is an error."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Result<T, E>","marks":[{"type":"code"}]},{"type":"text","text":" turns exceptions into values. "},{"type":"text","text":"getOrders","marks":[{"type":"code"}]},{"type":"text","text":" (step 6) returns "},{"type":"text","text":"Result<…, FetchError>","marks":[{"type":"code"}]},{"type":"text","text":", so the calling code has to handle the error – it can't be forgotten."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The generic ","marks":[{"type":"bold"}]},{"type":"text","text":"Select<T>","marks":[{"type":"code"}]},{"type":"text","text":" component","marks":[{"type":"bold"}]},{"type":"text","text":" takes options and a value of the same type. Instead of casting "},{"type":"text","text":"e.target.value as T","marks":[{"type":"code"}]},{"type":"text","text":" it looks the selected option up in the list, so the type is real, not just declared."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Don't generify up front.","marks":[{"type":"bold"}]},{"type":"text","text":" If a type parameter appears only once in a signature, you can almost always drop it and use a plain type."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"step-5-utility-types"},"content":[{"type":"text","text":"Step 5. Utility types"}]},{"type":"paragraph","content":[{"type":"text","text":"Utility types are functions on types: they turn one type into another. Thanks to them "},{"type":"text","text":"one model","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"Order","marks":[{"type":"code"}]},{"type":"text","text":") serves the form, the PATCH body, the list and the stats, instead of four hand-maintained copies."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Type"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"What it does"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Example in the project"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Pick<T, K>","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"Omit<T, K>","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"keeps / removes fields"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OrderDraft = Omit<Order, \"id\" | \"status\">","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Partial<T>","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"Required<T>","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"all fields optional / required"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OrderPatch","marks":[{"type":"code"}]},{"type":"text","text":" for PATCH"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Readonly<T>","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"read-only fields"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OrderSummary","marks":[{"type":"code"}]},{"type":"text","text":" in lists"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Record<K, V>","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"object keyed by "},{"type":"text","text":"K","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"StatusCounts","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"statusColors","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Extract<T, U>","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"Exclude<T, U>","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"filters a union"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ActiveStatus","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ReturnType<F>","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"Awaited<T>","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a function's / promise's result type"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OrdersResult","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"mapped type + "},{"type":"text","text":"as","marks":[{"type":"code"}]},{"type":"text","text":" + template literals"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"transforms keys"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"StatusHandlers","marks":[{"type":"code"}]},{"type":"text","text":" → "},{"type":"text","text":"onPlaced","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"onCooking","marks":[{"type":"code"}]},{"type":"text","text":"…"}]}]}]}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/lib/types.ts"},"content":[{"type":"text","text":"import type { getOrders } from \"../api/client.ts\";\nimport type { Order, OrderStatus } from \"../domain/order.ts\";\n\n// What the checkout form produces: the server assigns id and status.\nexport type OrderDraft = Omit<Order, \"id\" | \"status\">;\n\n// Body of PATCH /orders/:id – every field optional, only these two editable.\nexport type OrderPatch = Partial<Pick<Order, \"customer\" | \"note\">>;\n\n// A read-only projection for lists.\nexport type OrderSummary = Readonly<Pick<Order, \"id\" | \"customer\">> & { totalCents: number };\n\n// One counter per status kind – adding a kind forces you to handle it here.\nexport type StatusCounts = Record<OrderStatus[\"kind\"], number>;\n\n// Mapped type with key remapping and template literal types:\n// { onPlaced?: (s: {kind:\"placed\"...}) => void; onCooking?: ...; ... }\nexport type StatusHandlers = {\n  [S in OrderStatus as `on${Capitalize<S[\"kind\"]>}`]?: (status: S) => void;\n};\n\n// Types computed from code: follow the function, never copy its result type by hand.\nexport type OrdersResult = Awaited<ReturnType<typeof getOrders>>;"}]},{"type":"paragraph","content":[{"type":"text","text":"The last line matters: "},{"type":"text","text":"Awaited<ReturnType<typeof getOrders>>","marks":[{"type":"code"}]},{"type":"text","text":" "},{"type":"text","text":"follows the code","marks":[{"type":"bold"}]},{"type":"text","text":". Change what "},{"type":"text","text":"getOrders","marks":[{"type":"code"}]},{"type":"text","text":" returns and the type changes with it – every place that no longer fits gets a compile error."}]},{"type":"heading","attrs":{"level":2,"id":"step-6-typing-api-responses-with-zod"},"content":[{"type":"text","text":"Step 6. Typing API responses with Zod"}]},{"type":"paragraph","content":[{"type":"text","text":"This is the most important step of the guide. "},{"type":"text","text":"TypeScript types vanish at runtime.","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"const orders = await res.json() as Order[]","marks":[{"type":"code"}]},{"type":"text","text":" checks nothing – it merely promises the compiler that the server definitely sent what you expect. When the backend changes the format or returns an HTML error page, the app crashes three components later with a message that tells you nothing."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  A[\"fetch('/orders.json')\"] -->|\"json(): unknown\"| B[\"z.array(z.unknown())\"]\n  B --> C{\"OrderSchema.safeParse<br/>for every record\"}\n  C -->|\"success\"| D[\"transform:<br/>DTO → Order\"]\n  C -->|\"error\"| E[\"record skipped<br/>+ console warning\"]\n  D --> F[\"Result.ok({ orders, rejected })\"]\n  A -->|\"network / HTTP 5xx\"| G[\"Result.err(FetchError)\"]\n  F --> H[\"React components<br/>(fully typed)\"]\n  G --> H","caption":"The trust boundary: everything from outside is unknown until it passes a schema"}},{"type":"paragraph","content":[{"type":"text","text":"The Zod schema describes the "},{"type":"text","text":"wire format","marks":[{"type":"bold"}]},{"type":"text","text":" – snake_case, prices in grosze, dates as ISO strings – and "},{"type":"text","text":".transform()","marks":[{"type":"code"}]},{"type":"text","text":" maps it to the domain model. You derive "},{"type":"text","text":"OrderDto","marks":[{"type":"code"}]},{"type":"text","text":" from the schema with "},{"type":"text","text":"z.infer","marks":[{"type":"code"}]},{"type":"text","text":", so schema and type can't drift apart. The "},{"type":"text","text":"(dto): Order","marks":[{"type":"code"}]},{"type":"text","text":" annotation on "},{"type":"text","text":"transform","marks":[{"type":"code"}]},{"type":"text","text":" makes the compiler check the mapping result against the domain model."}]},{"type":"codeGroup","attrs":{"title":"Data, schemas and the API client"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"public/orders.json"},"content":[{"type":"text","text":"[\n  {\n    \"id\": \"ord_1042\",\n    \"customer\": \"Halina K.\",\n    \"lines\": [{ \"item_id\": \"ruskie-10\", \"name\": \"Ruskie (10 pcs)\", \"quantity\": 2, \"unit_price\": 3200 }],\n    \"status\": { \"type\": \"delivering\", \"courier\": \"Zdzisław\", \"eta_minutes\": 12 },\n    \"note\": \"Extra fried onion\"\n  },\n  {\n    \"id\": \"ord_1043\",\n    \"customer\": \"Marek W.\",\n    \"lines\": [\n      { \"item_id\": \"meat-6\", \"name\": \"Meat (6 pcs)\", \"quantity\": 1, \"unit_price\": 2400 },\n      { \"item_id\": \"cabbage-10\", \"name\": \"Cabbage & mushroom (10 pcs)\", \"quantity\": 1, \"unit_price\": 3400 }\n    ],\n    \"status\": { \"type\": \"cooking\", \"eta_minutes\": 18 }\n  },\n  {\n    \"id\": \"ord_1044\",\n    \"customer\": \"Ola P.\",\n    \"lines\": [{ \"item_id\": \"ruskie-20\", \"name\": \"Ruskie (20 pcs)\", \"quantity\": 1, \"unit_price\": 5900 }],\n    \"status\": { \"type\": \"delivered\", \"delivered_at\": \"2026-11-27T12:41:00Z\" }\n  },\n  {\n    \"id\": \"ord_1045\",\n    \"customer\": \"\",\n    \"lines\": [],\n    \"status\": { \"type\": \"teleported\" }\n  }\n]"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/api/schemas.ts"},"content":[{"type":"text","text":"import { z } from \"zod\";\nimport { toMenuItemId, toOrderId, type Order, type OrderStatus } from \"../domain/order.ts\";\n\n// Wire format: snake_case, prices in grosze, dates as ISO strings.\nconst StatusDtoSchema = z.discriminatedUnion(\"type\", [\n  z.object({ type: z.literal(\"placed\"), placed_at: z.iso.datetime() }),\n  z.object({ type: z.literal(\"cooking\"), eta_minutes: z.int().nonnegative() }),\n  z.object({ type: z.literal(\"delivering\"), courier: z.string().min(1), eta_minutes: z.int().nonnegative() }),\n  z.object({ type: z.literal(\"delivered\"), delivered_at: z.iso.datetime() }),\n  z.object({ type: z.literal(\"cancelled\"), reason: z.string() }),\n]);\n\nconst OrderLineDtoSchema = z.object({\n  item_id: z.string().min(1),\n  name: z.string().min(1),\n  quantity: z.int().positive(),\n  unit_price: z.int().nonnegative(),\n});\n\nexport const OrderDtoSchema = z.object({\n  id: z.string().regex(/^ord_\\d+$/, \"Expected an id like ord_123\"),\n  customer: z.string().min(1),\n  lines: z.array(OrderLineDtoSchema).min(1),\n  status: StatusDtoSchema,\n  note: z.string().max(200).optional(),\n});\n\n// The DTO type is derived from the schema – one source of truth, no drift.\nexport type OrderDto = z.infer<typeof OrderDtoSchema>;\n\nfunction toStatus(dto: OrderDto[\"status\"]): OrderStatus {\n  switch (dto.type) {\n    case \"placed\":\n      return { kind: \"placed\", placedAt: new Date(dto.placed_at) };\n    case \"cooking\":\n      return { kind: \"cooking\", etaMinutes: dto.eta_minutes };\n    case \"delivering\":\n      return { kind: \"delivering\", courier: dto.courier, etaMinutes: dto.eta_minutes };\n    case \"delivered\":\n      return { kind: \"delivered\", deliveredAt: new Date(dto.delivered_at) };\n    case \"cancelled\":\n      return { kind: \"cancelled\", reason: dto.reason };\n  }\n}\n\n// Validate the DTO and map it to the domain model in one step.\nexport const OrderSchema = OrderDtoSchema.transform(\n  (dto): Order => ({\n    id: toOrderId(dto.id),\n    customer: dto.customer,\n    lines: dto.lines.map((l) => ({\n      itemId: toMenuItemId(l.item_id),\n      name: l.name,\n      quantity: l.quantity,\n      unitPriceCents: l.unit_price,\n    })),\n    status: toStatus(dto.status),\n    note: dto.note,\n  }),\n);"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/api/client.ts"},"content":[{"type":"text","text":"import { z } from \"zod\";\nimport type { Order } from \"../domain/order.ts\";\nimport { errorMessage } from \"../lib/guards.ts\";\nimport { err, ok, type Result } from \"../lib/result.ts\";\nimport { OrderSchema } from \"./schemas.ts\";\n\nexport type FetchError =\n  | { type: \"network\"; message: string }\n  | { type: \"http\"; status: number; message: string }\n  | { type: \"invalid-data\"; details: string };\n\n// Generic over the schema: the return type is whatever the schema outputs.\nexport async function fetchJson<S extends z.ZodType>(\n  url: string,\n  schema: S,\n  init?: RequestInit,\n): Promise<Result<z.output<S>, FetchError>> {\n  let response: Response;\n  try {\n    response = await fetch(url, init);\n  } catch (e) {\n    return err({ type: \"network\", message: errorMessage(e) });\n  }\n  if (!response.ok) return err({ type: \"http\", status: response.status, message: response.statusText });\n\n  const json: unknown = await response.json(); // unknown, not any: you must validate before use\n  const parsed = schema.safeParse(json);\n  return parsed.success ? ok(parsed.data) : err({ type: \"invalid-data\", details: z.prettifyError(parsed.error) });\n}\n\n// One broken record should not blank the whole screen: validate item by item.\nexport async function getOrders(signal?: AbortSignal): Promise<Result<{ orders: Order[]; rejected: number }, FetchError>> {\n  const res = await fetchJson(\"/orders.json\", z.array(z.unknown()), { signal: signal ?? null });\n  if (!res.ok) return res;\n\n  const orders: Order[] = [];\n  let rejected = 0;\n  for (const raw of res.value) {\n    const parsed = OrderSchema.safeParse(raw);\n    if (parsed.success) orders.push(parsed.data);\n    else {\n      rejected++;\n      console.warn(\"Skipping invalid order:\\n\" + z.prettifyError(parsed.error));\n    }\n  }\n  return ok({ orders, rejected });\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Three design decisions worth copying into your own projects:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"fetchJson","marks":[{"type":"code"}]},{"type":"text","text":" is generic over the schema","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"S extends z.ZodType","marks":[{"type":"code"}]},{"type":"text","text":") and returns "},{"type":"text","text":"z.output<S>","marks":[{"type":"code"}]},{"type":"text","text":". The result type comes from the schema you pass – you don't state it twice."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Record-by-record validation.","marks":[{"type":"bold"}]},{"type":"text","text":" One broken record ("},{"type":"text","text":"ord_1045","marks":[{"type":"code"}]},{"type":"text","text":" in the sample data) doesn't blank the whole screen. It's skipped, and the number of rejected records reaches the UI. In an admin panel that's usually better than \"something went wrong\"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Errors as a union","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"FetchError","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"network","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"http","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"invalid-data","marks":[{"type":"code"}]},{"type":"text","text":"). The component knows what to show in each case, and an exhaustive "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" makes sure none is missed."}]}]}]},{"type":"prosCons","attrs":{"pros":["zero extra code and no extra kilobytes in the bundle","enough for data you create yourself in the same process","bad data stopped at the boundary, with a readable message (`z.prettifyError`)","type derived from the schema – a single source of truth"],"cons":["doesn't notice format changes on the server side","the error surfaces far from its cause, often only for the user","an extra dependency (a dozen-odd kB) and parsing cost for large responses"],"prosTitle":"Types only (`as`)","consTitle":"Runtime validation (Zod)"}},{"type":"heading","attrs":{"level":2,"id":"step-7-typescript-in-react-components"},"content":[{"type":"text","text":"Step 7. TypeScript in React components"}]},{"type":"paragraph","content":[{"type":"text","text":"Typing is simpler in React 19 than it used to be: "},{"type":"text","text":"ref","marks":[{"type":"code"}]},{"type":"text","text":" is a regular prop (no "},{"type":"text","text":"forwardRef","marks":[{"type":"code"}]},{"type":"text","text":"), and "},{"type":"text","text":"React.FC","marks":[{"type":"code"}]},{"type":"text","text":" isn't needed – just type the function's parameter. The key patterns:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Props as an intersection","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"{ order: Order } & Omit<ComponentProps<\"article\">, \"children\">","marks":[{"type":"code"}]},{"type":"text","text":". The component accepts every native attribute of the element ("},{"type":"text","text":"className","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"aria-*","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"data-*","marks":[{"type":"code"}]},{"type":"text","text":") and passes them on via "},{"type":"text","text":"...rest","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"State as a union","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"useState<LoadState>","marks":[{"type":"code"}]},{"type":"text","text":" with "},{"type":"text","text":"loading","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"error","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"ready","marks":[{"type":"code"}]},{"type":"text","text":" variants. There's no \"loading and failed at the same time\", and after "},{"type":"text","text":"if (state.status === \"error\")","marks":[{"type":"code"}]},{"type":"text","text":" you can read "},{"type":"text","text":"state.error","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Event types","marks":[{"type":"bold"}]},{"type":"text","text":": inline handlers ("},{"type":"text","text":"onChange={(e) => …}","marks":[{"type":"code"}]},{"type":"text","text":") are inferred. When the handler is defined separately, annotate it: "},{"type":"text","text":"ChangeEvent<HTMLInputElement>","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"as const satisfies","marks":[{"type":"code"}]},{"type":"text","text":" for constant options: literals stay exact ("},{"type":"text","text":"\"cooking\"","marks":[{"type":"code"}]},{"type":"text","text":", not "},{"type":"text","text":"string","marks":[{"type":"code"}]},{"type":"text","text":") and the shape is checked."}]}]}]},{"type":"codeGroup","attrs":{"title":"Components and the app"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/components/OrderCard.tsx"},"content":[{"type":"text","text":"import type { ComponentProps } from \"react\";\nimport type { Order, OrderId } from \"../domain/order.ts\";\nimport { describeStatus, isActive, totalCents } from \"../domain/status.ts\";\nimport { formatPrice } from \"../lib/guards.ts\";\nimport { statusColors } from \"./statusColors.ts\";\n\n// Own props + every native <article> prop except children (we render our own).\ntype OrderCardProps = {\n  order: Order;\n  onCancel?: (id: OrderId) => void;\n} & Omit<ComponentProps<\"article\">, \"children\">;\n\nexport function OrderCard({ order, onCancel, style, ...rest }: OrderCardProps) {\n  const { status } = order;\n  return (\n    <article\n      {...rest}\n      style={{ border: \"1px solid #dee2e6\", borderRadius: 8, padding: 12, opacity: status.kind === \"cancelled\" ? 0.6 : 1, ...style }}\n    >\n      <header>\n        <strong>{order.customer}</strong> · {formatPrice(totalCents(order))}\n      </header>\n      <p style={{ color: statusColors[status.kind], margin: \"6px 0\" }}>{describeStatus(status)}</p>\n      {order.note && <p style={{ margin: 0 }}><em>{order.note}</em></p>}\n      {/* isActive() is a type predicate – inside, status is \"cooking\" | \"delivering\" */}\n      {isActive(status) && onCancel && (\n        <button type=\"button\" onClick={() => onCancel(order.id)}>\n          Cancel ({status.etaMinutes} min left)\n        </button>\n      )}\n    </article>\n  );\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/App.tsx"},"content":[{"type":"text","text":"import { useEffect, useMemo, useState, type ChangeEvent } from \"react\";\nimport { getOrders, type FetchError } from \"./api/client.ts\";\nimport { OrderCard } from \"./components/OrderCard.tsx\";\nimport { Select } from \"./components/Select.tsx\";\nimport type { Order, OrderId, OrderStatusKind } from \"./domain/order.ts\";\nimport { groupBy } from \"./lib/result.ts\";\n\n// UI state as a discriminated union: no \"loading + error + data\" combinations that make no sense.\ntype LoadState =\n  | { status: \"loading\" }\n  | { status: \"error\"; error: FetchError }\n  | { status: \"ready\"; orders: Order[]; rejected: number };\n\ntype StatusFilter = OrderStatusKind | \"all\";\n\nconst filterOptions = [\n  { value: \"all\", label: \"All\" },\n  { value: \"placed\", label: \"Placed\" },\n  { value: \"cooking\", label: \"Cooking\" },\n  { value: \"delivering\", label: \"Delivering\" },\n  { value: \"delivered\", label: \"Delivered\" },\n  { value: \"cancelled\", label: \"Cancelled\" },\n] as const satisfies readonly { value: StatusFilter; label: string }[];\n\nfunction errorText(error: FetchError): string {\n  switch (error.type) {\n    case \"network\":\n      return `No connection: ${error.message}`;\n    case \"http\":\n      return `Server error ${error.status}`;\n    case \"invalid-data\":\n      return \"The server sent data we do not understand\";\n  }\n}\n\nexport default function App() {\n  const [state, setState] = useState<LoadState>({ status: \"loading\" });\n  const [filter, setFilter] = useState<StatusFilter>(\"all\");\n  const [query, setQuery] = useState(\"\");\n\n  useEffect(() => {\n    const controller = new AbortController();\n    getOrders(controller.signal).then((res) => {\n      if (controller.signal.aborted) return;\n      setState(res.ok ? { status: \"ready\", ...res.value } : { status: \"error\", error: res.error });\n    });\n    return () => controller.abort();\n  }, []);\n\n  const orders = state.status === \"ready\" ? state.orders : [];\n  const visible = useMemo(\n    () =>\n      orders.filter(\n        (o) => (filter === \"all\" || o.status.kind === filter) && o.customer.toLowerCase().includes(query.toLowerCase()),\n      ),\n    [orders, filter, query],\n  );\n  const counts = groupBy(orders, (o) => o.status.kind);\n\n  // Explicit event type when the handler is declared outside JSX.\n  const handleQuery = (e: ChangeEvent<HTMLInputElement>) => setQuery(e.target.value);\n\n  const cancel = (id: OrderId) =>\n    setState((s) =>\n      s.status !== \"ready\"\n        ? s\n        : {\n            ...s,\n            orders: s.orders.map((o) =>\n              o.id === id ? { ...o, status: { kind: \"cancelled\", reason: \"Cancelled by the customer\" } } : o,\n            ),\n          },\n    );\n\n  if (state.status === \"loading\") return <p>Loading orders…</p>;\n  if (state.status === \"error\") return <p role=\"alert\">{errorText(state.error)}</p>;\n\n  return (\n    <main style={{ fontFamily: \"system-ui\", maxWidth: 640, margin: \"24px auto\", display: \"grid\", gap: 12 }}>\n      <h1>Orders</h1>\n      <div style={{ display: \"flex\", gap: 12, flexWrap: \"wrap\" }}>\n        <Select label=\"Status\" value={filter} options={filterOptions} onChange={setFilter} />\n        <input placeholder=\"Customer…\" value={query} onChange={handleQuery} />\n      </div>\n      <small>\n        In the kitchen: {counts.cooking?.length ?? 0} · On the way: {counts.delivering?.length ?? 0}\n        {state.rejected > 0 && ` · ${state.rejected} invalid record(s) skipped`}\n      </small>\n      {visible.map((order) => (\n        <OrderCard key={order.id} order={order} onCancel={cancel} />\n      ))}\n    </main>\n  );\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/main.tsx"},"content":[{"type":"text","text":"import { StrictMode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport App from \"./App.tsx\";\nimport { assertDefined } from \"./lib/guards.ts\";\n\nconst container = document.getElementById(\"root\");\nassertDefined(container, \"#root element\"); // instead of the `!` non-null assertion\n\ncreateRoot(container).render(\n  <StrictMode>\n    <App />\n  </StrictMode>,\n);"}]}]},{"type":"paragraph","content":[{"type":"text","text":"useEffect","marks":[{"type":"code"}]},{"type":"text","text":" aborts the request with an "},{"type":"text","text":"AbortController","marks":[{"type":"code"}]},{"type":"text","text":" when the component unmounts (or when StrictMode mounts it twice in development). In the "},{"type":"text","text":"React guide","marks":[{"type":"link","attrs":{"href":"/en/articles/react"}}]},{"type":"text","text":" you'll replace this fetching with TanStack Query, which handles caching, retries and loading states for you."}]},{"type":"heading","attrs":{"level":2,"id":"step-8-the-same-code-in-node-no-build-step"},"content":[{"type":"text","text":"Step 8. The same code in Node – no build step"}]},{"type":"paragraph","content":[{"type":"text","text":"Node 24 (and 22.18+) does "},{"type":"text","text":"type stripping","marks":[{"type":"bold"}]},{"type":"text","text":" by default: it runs a "},{"type":"text","text":".ts","marks":[{"type":"code"}]},{"type":"text","text":" file as if it were JavaScript with the annotations removed. No build step, no "},{"type":"text","text":"ts-node","marks":[{"type":"code"}]},{"type":"text","text":". There's one condition: erasable syntax only, which is exactly what "},{"type":"text","text":"erasableSyntaxOnly","marks":[{"type":"code"}]},{"type":"text","text":" enforces. The script uses the same schemas and domain functions as the browser app:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"scripts/check-orders.ts"},"content":[{"type":"text","text":"// Run with plain Node 24: `node scripts/check-orders.ts` – types are stripped, nothing is compiled.\nimport { readFile } from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { OrderSchema } from \"../src/api/schemas.ts\";\nimport { describeStatus, totalCents } from \"../src/domain/status.ts\";\n\nconst file = new URL(\"../public/orders.json\", import.meta.url);\nconst items = z.array(z.unknown()).parse(JSON.parse(await readFile(file, \"utf8\")));\n\nlet failed = 0;\nfor (const [index, item] of items.entries()) {\n  const result = OrderSchema.safeParse(item);\n  if (result.success) {\n    const order = result.data;\n    console.log(`OK   ${order.id} ${order.customer}: ${describeStatus(order.status)}, ${totalCents(order) / 100} PLN`);\n  } else {\n    failed++;\n    console.error(`FAIL item #${index}\\n${z.prettifyError(result.error)}`);\n  }\n}\nprocess.exitCode = failed > 0 ? 1 : 0;"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm run check:orders\n# OK   ord_1042 Halina K.: Zdzisław is on the way (12 min), 64 PLN\n# OK   ord_1043 Marek W.: In the kitchen, ready in ~18 min, 58 PLN\n# OK   ord_1044 Ola P.: Delivered at 1:41:00 PM, 59 PLN\n# FAIL item #3\n# ✖ Too small: expected string to have >=1 characters\n#   → at customer\n# ..."}]},{"type":"paragraph","content":[{"type":"text","text":"The split of roles is simple: "},{"type":"text","text":"Node and Vite run the code, ","marks":[{"type":"bold"}]},{"type":"text","text":"tsc","marks":[{"type":"code"}]},{"type":"text","text":" only checks it.","marks":[{"type":"bold"}]},{"type":"text","text":" In CI you run "},{"type":"text","text":"npm run typecheck","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"tsc -b","marks":[{"type":"code"}]},{"type":"text","text":"), and in the editor the TypeScript 7 language server stays fast even in large monorepos. If you publish a library you still compile it to "},{"type":"text","text":".js","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":".d.ts","marks":[{"type":"code"}]},{"type":"text","text":", but apps and scripts don't need that."}]},{"type":"heading","attrs":{"level":2,"id":"common-pitfalls"},"content":[{"type":"text","text":"Common pitfalls"}]},{"type":"paragraph","content":[{"type":"text","text":"The most dangerous TypeScript bugs are the ones that "},{"type":"text","text":"compile","marks":[{"type":"bold"}]},{"type":"text","text":". Every snippet below passes "},{"type":"text","text":"tsc","marks":[{"type":"code"}]},{"type":"text","text":" without a warning and ends in a runtime error or a silent "},{"type":"text","text":"NaN","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"examples/pitfalls.ts"},"content":[{"type":"text","text":"// Everything below COMPILES – that is exactly the problem.\n\n// 1. `as` is a promise to the compiler, not a conversion or a check.\ntype Customer = { id: number; email: string };\nconst customer = JSON.parse('{\"id\":\"7\"}') as Customer; // id is a string, email is missing\nconsole.log(customer.email.toLowerCase()); // TypeError at runtime\n\n// 2. `any` is contagious: whatever touches it loses its type.\nfunction legacyTotal(): any {\n  return { total: \"12.50\" };\n}\nconst total: number = legacyTotal().total; // a string pretending to be a number\nconsole.log(total.toFixed(2)); // TypeError at runtime\n\n// 3. Optional chaining hides a missing value instead of handling it.\ntype Delivery = { courier?: { name: string; etaMinutes: number } };\nconst delivery: Delivery = {};\nconsole.log(`Ready in ${delivery.courier?.etaMinutes} min`); // \"Ready in undefined min\"\n\n// 4. The non-null assertion `!` just moves the crash elsewhere.\nconst prices = new Map<string, number>([[\"ruskie\", 32]]);\nconsole.log(prices.get(\"pierogi-z-mięsem\")! * 2); // NaN, no error\n\n// 5. Object.keys() returns string[] on purpose – objects may carry extra keys at runtime.\nconst menu = { ruskie: 32, meat: 36 };\nfor (const key of Object.keys(menu) as (keyof typeof menu)[]) {\n  console.log(key, menu[key]); // OK only because WE know there are no extra keys\n}\n\n// Safer alternatives: `unknown` + schema (zod), narrowing, explicit undefined handling,\n// Object.entries(), and string unions instead of enums."}]},{"type":"callout","attrs":{"variant":"danger","title":"Common mistake: `as` on an API response"},"content":[{"type":"paragraph","content":[{"type":"text","text":"await res.json() as Order[]","marks":[{"type":"code"}]},{"type":"text","text":" is the most common cause of \"undefined is not a function\" errors in apps written in TypeScript. A cast doesn't convert or check anything – it only switches the compiler off. Always treat data from the network, "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"postMessage","marks":[{"type":"code"}]},{"type":"text","text":" or URL parameters as "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" and run it through a schema."}]}]},{"type":"paragraph","content":[{"type":"text","text":"A few less obvious rules:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Keep ","marks":[{"type":"bold"}]},{"type":"text","text":"any","marks":[{"type":"code"}]},{"type":"text","text":" for migration code","marks":[{"type":"bold"}]},{"type":"text","text":", marked with a TODO comment. In new code use "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" – it forces narrowing."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Literal unions instead of ","marks":[{"type":"bold"}]},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":".","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"type Tag = \"vegan\" | \"spicy\"","marks":[{"type":"code"}]},{"type":"text","text":" emits no code, works with "},{"type":"text","text":"erasableSyntaxOnly","marks":[{"type":"code"}]},{"type":"text","text":" and can be iterated via an "},{"type":"text","text":"as const","marks":[{"type":"code"}]},{"type":"text","text":" array."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Object.keys()","marks":[{"type":"code"}]},{"type":"text","text":" returns ","marks":[{"type":"bold"}]},{"type":"text","text":"string[]","marks":[{"type":"code"}]},{"type":"text","text":" on purpose","marks":[{"type":"bold"}]},{"type":"text","text":" – an object can have more keys at runtime than its type says. Cast only when you created the object yourself."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Replace ","marks":[{"type":"bold"}]},{"type":"text","text":"// @ts-ignore","marks":[{"type":"code"}]},{"type":"text","text":" with ","marks":[{"type":"bold"}]},{"type":"text","text":"// @ts-expect-error","marks":[{"type":"code"}]},{"type":"text","text":" – the latter reports an error once the problem disappears, so it doesn't linger forever."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"cheat-sheet-what-to-use-when"},"content":[{"type":"text","text":"Cheat sheet: what to use when"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Situation"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Tool"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"An object others extend (props, contract)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"interface","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Several mutually exclusive states"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"discriminated union + "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" with "},{"type":"text","text":"assertNever","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Data from the network, files, forms"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" + Zod schema, type via "},{"type":"text","text":"z.infer","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Constant config, colour maps, options"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"as const satisfies …","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Ids that must not be mixed up"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"branded types"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"A function that works for many types"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a generic with a constraint ("},{"type":"text","text":"extends","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"A variant of an existing model (form, PATCH)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Pick","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Omit","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Partial","marks":[{"type":"code"}]},{"type":"text","text":" instead of a copy"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"check-yourself"},"content":[{"type":"text","text":"Check yourself"}]},{"type":"quiz","attrs":{"question":"You add a new variant `{ kind: \"refunded\"; amountCents: number }` to `OrderStatus`. What happens to `describeStatus`?","multiple":false,"options":[{"text":"Nothing – it returns `undefined` for the new status","correct":false,"explanation":"That would be true without the `default` branch calling `assertNever`. In this project the compiler reports an error."},{"text":"The project stops compiling at the `assertNever(status)` line","correct":true,"explanation":"Correct. The `default` branch is left with `{ kind: \"refunded\" … }`, which isn't assignable to `never`."},{"text":"TypeScript adds the missing `case` automatically","correct":false,"explanation":"The compiler doesn't write code – it only points at the place you need to complete."}]}},{"type":"quiz","attrs":{"question":"Which line types a `fetch` response best?","multiple":false,"options":[{"text":"`const data = (await res.json()) as Order[]`","correct":false,"explanation":"A cast checks nothing. When the server changes the format, the error surfaces far from its cause."},{"text":"`const data: any = await res.json()`","correct":false,"explanation":"`any` switches type checking off for everything it touches."},{"text":"`const data = OrderListSchema.parse(await res.json())`","correct":true,"explanation":"Correct. The schema validates the data at runtime and the result type is derived from it."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: how is "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" different from "},{"type":"text","text":"any","marks":[{"type":"code"}]},{"type":"text","text":", and when do you use "},{"type":"text","text":"never","marks":[{"type":"code"}]},{"type":"text","text":"?"}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"any","marks":[{"type":"code"}]},{"type":"text","text":" turns type checking off: the value can be assigned anywhere and you can call anything on it, and it \"infects\" everything it touches. "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" is the safe counterpart – anything can be assigned to it, but before using it you must narrow the type ("},{"type":"text","text":"typeof","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"instanceof","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"in","marks":[{"type":"code"}]},{"type":"text","text":", a schema). That's why "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" is the right type for external data and for "},{"type":"text","text":"catch (e)","marks":[{"type":"code"}]},{"type":"text","text":". "},{"type":"text","text":"never","marks":[{"type":"code"}]},{"type":"text","text":" is the type with no values: functions that always throw return it, and it's what remains in the "},{"type":"text","text":"default","marks":[{"type":"code"}]},{"type":"text","text":" branch of an exhaustive "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":". Assigning anything to "},{"type":"text","text":"never","marks":[{"type":"code"}]},{"type":"text","text":" is an error, which is why "},{"type":"text","text":"assertNever(x: never)","marks":[{"type":"code"}]},{"type":"text","text":" turns an unhandled union variant into a compile error."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"what-next"},"content":[{"type":"text","text":"What next"}]},{"type":"linkCard","attrs":{"url":"/en/topics/react","title":"React","description":"Components, hooks, TanStack Query and forms with react-hook-form + Zod","kind":"topic","ref":"react"}},{"type":"linkCard","attrs":{"url":"/en/topics/state","title":"State","description":"When a discriminated union is enough and when you need the State pattern","kind":"topic","ref":"state"}},{"type":"linkCard","attrs":{"url":"/en/topics/adapter","title":"Adapter","description":"Mapping a DTO to the domain model is an adapter at the system boundary","kind":"topic","ref":"adapter"}},{"type":"linkCard","attrs":{"url":"/en/topics/mui","title":"MUI","description":"A typed theme and custom component variants in Material UI","kind":"topic","ref":"mui"}}]},"toc":[{"id":"step-0-a-project-and-a-tsconfig-that-actually-guards-you","text":"Step 0. A project and a tsconfig that actually guards you","level":2,"locked":false},{"id":"step-1-types-or-interfaces","text":"Step 1. Types or interfaces?","level":2,"locked":false},{"id":"step-2-discriminated-unions-and-an-exhaustive-switch","text":"Step 2. Discriminated unions and an exhaustive switch","level":2,"locked":false},{"id":"step-3-narrowing","text":"Step 3. Narrowing","level":2,"locked":false},{"id":"step-4-generics-without-fear","text":"Step 4. Generics without fear","level":2,"locked":false},{"id":"step-5-utility-types","text":"Step 5. Utility types","level":2,"locked":false},{"id":"step-6-typing-api-responses-with-zod","text":"Step 6. Typing API responses with Zod","level":2,"locked":false},{"id":"step-7-typescript-in-react-components","text":"Step 7. TypeScript in React components","level":2,"locked":false},{"id":"step-8-the-same-code-in-node-no-build-step","text":"Step 8. The same code in Node – no build step","level":2,"locked":false},{"id":"common-pitfalls","text":"Common pitfalls","level":2,"locked":false},{"id":"cheat-sheet-what-to-use-when","text":"Cheat sheet: what to use when","level":2,"locked":false},{"id":"check-yourself","text":"Check yourself","level":2,"locked":false},{"id":"what-next","text":"What next","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":78,"visibleBlocks":78,"resources":[{"id":"6b0857c23c96f2d34d0b44a2","type":"article","provider":"web","url":"https://khalilstemmler.com/articles/typescript-domain-driven-design/make-illegal-states-unrepresentable","embedUrl":null,"title":"Make Illegal States Unrepresentable! - Domain-Driven Design w/ TypeScript | Khalil Stemmler","description":"By using TypeScript's static type system, not only can we enforce (typically challenging things like) business rules and error states, but we can create a domain-specific language so well-defined that it becomes virtually impossible for any future code to be written that puts the system in an…","author":"Khalil Stemmler","thumbnailUrl":"https://khalilstemmler.com/img/blog/templates/banners/ddd-blog-banner.png","durationSec":null,"lang":"en","topics":["ddd-strategic-design"],"techs":["typescript"],"tags":["software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":50,"verifiedAt":"2026-11-26T11:29:24.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c43c96f2d34d0b4713","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL21655070W","embedUrl":null,"title":"Effective TypeScript","description":"","author":"Dan Vanderkam","thumbnailUrl":"https://covers.openlibrary.org/b/id/10677564-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["typescript"],"tags":["book"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2019-01-01T00:00:00.000Z","popularity":36,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"},{"id":"6b0857bd3c96f2d34d0b40d0","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/typescripts-compiler-glow-up-openais-agentic-push-and/id1700169000?i=1000699482268","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id1700169000?i=1000699482268","title":"TypeScript’s Compiler Glow-Up, OpenAI’s Agentic Push, and One-Click Site Cloning","description":"The TypeScript Compiler (TSC) is getting a major port to Go. Go’s support for concurrency and efficient memory management convinced the Microsoft team to port the code over and should result in as much as 10x faster builds in the future. Expect a feature-complete implementation towards the end of…","author":"Front-End Fire","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts221/v4/8c/fb/fd/8cfbfdfe-aa7c-9bf7-7539-e165832595b1/mza_11977879437405956906.jpg/600x600bb.jpg","durationSec":2657,"lang":"en","topics":["ai-agents","ai-in-node"],"techs":["typescript"],"tags":["podcast","ai","observability"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2025-03-17T10:00:00.000Z","popularity":40,"verifiedAt":"2026-11-26T11:06:11.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857b23c96f2d34d0b34a9","type":"repo","provider":"github","url":"https://github.com/labs42io/clean-code-typescript","embedUrl":null,"title":"labs42io/clean-code-typescript","description":"Clean Code concepts adapted for TypeScript","author":"labs42io","thumbnailUrl":"https://opengraph.githubassets.com/1/labs42io/clean-code-typescript","durationSec":null,"lang":"en","topics":["clean-architecture"],"techs":["typescript"],"tags":["best-practices","clean-architecture","clean-code","coding-guidelines","principles","solid","software-architecture","typescript"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2019-01-22T16:58:12.000Z","popularity":77,"verifiedAt":"2026-11-26T10:57:47.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"},{"id":"6b0857c43c96f2d34d0b4775","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL19922533W","embedUrl":null,"title":"Programming TypeScript","description":"","author":"","thumbnailUrl":"https://covers.openlibrary.org/b/id/10312489-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["javascript","typescript"],"tags":["book"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2019-01-01T00:00:00.000Z","popularity":30,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.480Z","updatedAt":"2026-11-26T16:01:07.480Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}