{"id":"6b0941815ce40d447918f2fd","slug":"typescript","title":"TypeScript dla programistów React i Node – od typów do bezpiecznego API","summary":"Praktyczny poradnik TypeScript 7 na jednym projekcie – panelu zamówień pierogarni w React i skrypcie Node. Typy kontra interfejsy, unie dyskryminowane, zawężanie, generyki, typy narzędziowe, strict tsconfig i walidacja odpowiedzi API w Zod.","servedLang":"pl","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":25,"stats":{"views":5,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:25.168Z","updatedAt":"2026-11-27T12:28:14.582Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"TypeScript 7 w praktyce dla React i Node.js – type vs interface, generyki, narrowing, discriminated unions, utility types, strict tsconfig, Zod do typowania odpowiedzi API, uruchamianie .ts w Node 24 i typowe pułapki.","wordCount":4925,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"TypeScript nie służy do tego, żeby kompilator przestał się czepiać. Ma sprawić, że błędne stany aplikacji w ogóle nie dadzą się zapisać w kodzie. W tym poradniku zbudujesz mały, ale kompletny projekt: panel zamówień pierogarni w React i skrypt Node, który sprawdza dane z API. Po drodze przejdziesz przez wszystko, czego używa się na co dzień – od wyboru między "},{"type":"text","text":"type","marks":[{"type":"code"}]},{"type":"text","text":" a "},{"type":"text","text":"interface","marks":[{"type":"code"}]},{"type":"text","text":" po walidację JSON-a z serwera."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Modeluj "},{"type":"text","text":"stany","marks":[{"type":"bold"}]},{"type":"text","text":", a nie same pola: unia dyskryminowana ("},{"type":"text","text":"kind: \"cooking\" | \"delivering\" | …","marks":[{"type":"code"}]},{"type":"text","text":") i wyczerpujący "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" sprawiają, że nowy status zamówienia psuje kompilację wszędzie tam, gdzie trzeba go obsłużyć."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Dane z zewnątrz (API, "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":", formularze) mają typ "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":", dopóki nie przejdą przez schemat. "},{"type":"text","text":"Zod","marks":[{"type":"bold"}]},{"type":"text","text":" waliduje je w runtime, a typ wyprowadzasz ze schematu, zamiast przepisywać go ręcznie."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"TypeScript 7","marks":[{"type":"bold"}]},{"type":"text","text":" to natywny kompilator (8–12 razy szybsze pełne buildy), a od wersji 6.0 "},{"type":"text","text":"strict","marks":[{"type":"code"}]},{"type":"text","text":" jest domyślnie włączony. Node 24 uruchamia pliki "},{"type":"text","text":".ts","marks":[{"type":"code"}]},{"type":"text","text":" bez kompilacji, o ile używasz składni, którą da się po prostu wymazać."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Aplikację Vite + React 19, która pobiera listę zamówień z "},{"type":"text","text":"/orders.json","marks":[{"type":"code"}]},{"type":"text","text":", waliduje każdy rekord schematem Zod, mapuje go z formatu API (snake_case, ceny w groszach) na model domeny i pokazuje karty zamówień z filtrem statusu. Do tego skrypt "},{"type":"text","text":"node scripts/check-orders.ts","marks":[{"type":"code"}]},{"type":"text","text":", który na tych samych typach i schematach sprawdza plik z danymi. Cały kod (21 plików) pobierzesz jednym kliknięciem jako ZIP z ikony pobierania przy artykule."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 24 (albo 22.18+), podstawy JavaScriptu (ES2015+, "},{"type":"text","text":"async/await","marks":[{"type":"code"}]},{"type":"text","text":", moduły) i Reacta (komponent, props, "},{"type":"text","text":"useState","marks":[{"type":"code"}]},{"type":"text","text":"). Nie musisz znać wcześniejszych wersji TypeScriptu."}]},{"type":"stats","attrs":{"items":[{"value":"7.0","label":"wersja TypeScript","hint":"natywny kompilator napisany w Go"},{"value":"8–12×","label":"szybsze pełne buildy","hint":"według zespołu TypeScript"},{"value":"strict","label":"domyślnie od 6.0","hint":"nie musisz już włączać ręcznie"},{"value":"0","label":"`any` w kodzie aplikacji","hint":"`unknown` + schemat zamiast zgadywania"}]}},{"type":"heading","attrs":{"level":2,"id":"krok-0-projekt-i-tsconfig-ktory-naprawde-pilnuje"},"content":[{"type":"text","text":"Krok 0. Projekt i tsconfig, który naprawdę pilnuje"}]},{"type":"paragraph","content":[{"type":"text","text":"Zacznij od szablonu Vite – generuje dwa pliki konfiguracji: jeden dla kodu w przeglądarce, drugi dla plików uruchamianych przez Node (konfiguracja Vite, skrypty)."}]},{"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 był wersją przejściową, która przestawiła kilka wartości domyślnych, a 7.0 usunęła stare opcje na dobre. Jeśli przenosisz starszy projekt, to są zmiany, które najczęściej zaskakują:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Opcja"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Teraz (6.0/7.0)"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Co to znaczy w praktyce"}]}]}]},{"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":" domyślnie"}]}]},{"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":" i niejawne "},{"type":"text","text":"any","marks":[{"type":"code"}]},{"type":"text","text":" są błędami od pierwszego dnia"}]}]}]},{"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":" domyślnie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"globalne typy ("},{"type":"text","text":"process","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"describe","marks":[{"type":"code"}]},{"type":"text","text":") trzeba wskazać jawnie, np. "},{"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":" / najnowszy ES"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"koniec z kompilacją do ES5 – najniższy cel to 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":"usunięte w 7.0"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"używaj "},{"type":"text","text":"bundler","marks":[{"type":"code"}]},{"type":"text","text":" (Vite) albo "},{"type":"text","text":"nodenext","marks":[{"type":"code"}]},{"type":"text","text":" (Node) i aliasów przez "},{"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":"niedozwolone"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"domyślny import z pakietów CommonJS po prostu działa"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Oto konfiguracja projektu. Do ustawień z szablonu dodaliśmy "},{"type":"text","text":"noUncheckedIndexedAccess","marks":[{"type":"code"}]},{"type":"text","text":" (indeks tablicy lub rekordu może zwrócić "},{"type":"text","text":"undefined","marks":[{"type":"code"}]},{"type":"text","text":") i "},{"type":"text","text":"noImplicitOverride","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja projektu"},"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":"Na kilka flag warto zwrócić uwagę:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"verbatimModuleSyntax","marks":[{"type":"code"}]},{"type":"text","text":" – importy używane tylko jako typy muszą mieć "},{"type":"text","text":"import type","marks":[{"type":"code"}]},{"type":"text","text":". Dzięki temu narzędzia, które tylko wymazują typy (Vite, Node), nie muszą zgadywać, co usunąć."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"erasableSyntaxOnly","marks":[{"type":"code"}]},{"type":"text","text":" – zakazuje konstrukcji generujących kod w runtime: "},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"namespace","marks":[{"type":"code"}]},{"type":"text","text":" z wartościami i właściwości w parametrach konstruktora ("},{"type":"text","text":"constructor(private x: number)","marks":[{"type":"code"}]},{"type":"text","text":"). Zamiast "},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":" używasz unii literałów."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"allowImportingTsExtensions","marks":[{"type":"code"}]},{"type":"text","text":" – importujesz "},{"type":"text","text":"./App.tsx","marks":[{"type":"code"}]},{"type":"text","text":", a nie "},{"type":"text","text":"./App","marks":[{"type":"code"}]},{"type":"text","text":". Tak samo zapisany import zrozumie Vite i Node."}]}]},{"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":" ma typ "},{"type":"text","text":"Order | undefined","marks":[{"type":"code"}]},{"type":"text","text":". Na początku bywa to irytujące, ale łapie prawdziwe błędy z pustymi listami."}]}]}]},{"type":"callout","attrs":{"variant":"warning","title":"„Cannot find name 'process'” po aktualizacji"},"content":[{"type":"paragraph","content":[{"type":"text","text":"To skutek domyślnego "},{"type":"text","text":"\"types\": []","marks":[{"type":"code"}]},{"type":"text","text":". Kompilator nie ładuje już automatycznie wszystkich pakietów "},{"type":"text","text":"@types/*","marks":[{"type":"code"}]},{"type":"text","text":". Dopisz potrzebne do tablicy "},{"type":"text","text":"types","marks":[{"type":"code"}]},{"type":"text","text":" w odpowiednim pliku: "},{"type":"text","text":"[\"node\"]","marks":[{"type":"code"}]},{"type":"text","text":" dla skryptów, "},{"type":"text","text":"[\"vite/client\"]","marks":[{"type":"code"}]},{"type":"text","text":" dla aplikacji, "},{"type":"text","text":"[\"vitest/globals\"]","marks":[{"type":"code"}]},{"type":"text","text":" dla testów."}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-1-typy-czy-interfejsy"},"content":[{"type":"text","text":"Krok 1. Typy czy interfejsy?"}]},{"type":"paragraph","content":[{"type":"text","text":"To najczęstsze pytanie i dobra wiadomość jest taka, że dla zwykłych obiektów oba zapisy działają prawie tak samo. Różnice są w szczegółach:"}]},{"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":"Kształt obiektu"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Unie, krotki, typy prymitywne"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak ("},{"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":"Typy mapowane i warunkowe"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak ("},{"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":"Rozszerzanie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"extends","marks":[{"type":"code"}]},{"type":"text","text":", czytelne błędy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"&","marks":[{"type":"code"}]},{"type":"text","text":" (przecięcie), błędy bywają mniej czytelne"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Łączenie deklaracji (declaration merging)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak – dwie deklaracje o tej samej nazwie się sumują"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie – duplikat to błąd"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Praktyczna zasada, która sprawdza się w zespołach: "},{"type":"text","text":"interface","marks":[{"type":"code"}]},{"type":"text","text":" dla kształtów obiektów, które ktoś rozszerza (kontrakty, props, modele), ","marks":[{"type":"bold"}]},{"type":"text","text":"type","marks":[{"type":"code"}]},{"type":"text","text":" dla wszystkiego, co jest unią albo powstaje z innych typów.","marks":[{"type":"bold"}]},{"type":"text","text":" Najważniejsze jest to, żeby zespół trzymał się jednej konwencji."}]},{"type":"paragraph","content":[{"type":"text","text":"Model domeny pierogarni pokazuje oba zapisy. Zwróć uwagę na "},{"type":"text","text":"typy z markerem (branded types)","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"OrderId","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"MenuItemId","marks":[{"type":"code"}]},{"type":"text","text":" to w runtime zwykłe stringi, ale kompilator nie pozwoli przekazać jednego w miejsce drugiego:"}]},{"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":"Ten marker ("},{"type":"text","text":"__brand","marks":[{"type":"code"}]},{"type":"text","text":") istnieje tylko w systemie typów. Jedynym miejscem, gdzie zwykły string staje się "},{"type":"text","text":"OrderId","marks":[{"type":"code"}]},{"type":"text","text":", są funkcje "},{"type":"text","text":"toOrderId","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"toMenuItemId","marks":[{"type":"code"}]},{"type":"text","text":". Wywołasz je w warstwie, która waliduje dane z API, i nigdzie indziej."}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-unie-dyskryminowane-i-wyczerpujacy-switch"},"content":[{"type":"text","text":"Krok 2. Unie dyskryminowane i wyczerpujący switch"}]},{"type":"paragraph","content":[{"type":"text","text":"Klasyczny błąd modelowania to jeden obiekt z polami opcjonalnymi: "},{"type":"text","text":"status: string; courier?: string; etaMinutes?: number; reason?: string","marks":[{"type":"code"}]},{"type":"text","text":". Taki typ pozwala zapisać zamówienie „anulowane, z kurierem w drodze i bez powodu anulowania”. "},{"type":"text","text":"Unia dyskryminowana (discriminated union)","marks":[{"type":"bold"}]},{"type":"text","text":" opisuje każdy stan osobno, a wspólne pole "},{"type":"text","text":"kind","marks":[{"type":"code"}]},{"type":"text","text":" mówi kompilatorowi, który wariant właśnie obsługujesz."}]},{"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":"Zamówienie jako maszyna stanów – każdy stan ma tylko swoje pola"}},{"type":"paragraph","content":[{"type":"text","text":"Wewnątrz "},{"type":"text","text":"case \"delivering\"","marks":[{"type":"code"}]},{"type":"text","text":" TypeScript wie, że istnieje "},{"type":"text","text":"status.courier","marks":[{"type":"code"}]},{"type":"text","text":". W gałęzi "},{"type":"text","text":"default","marks":[{"type":"code"}]},{"type":"text","text":" zostaje typ "},{"type":"text","text":"never","marks":[{"type":"code"}]},{"type":"text","text":". Jeśli ktoś doda status "},{"type":"text","text":"\"refunded\"","marks":[{"type":"code"}]},{"type":"text","text":" i zapomni go obsłużyć, wywołanie "},{"type":"text","text":"assertNever(status)","marks":[{"type":"code"}]},{"type":"text","text":" przestanie się kompilować:"}]},{"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":"Funkcja "},{"type":"text","text":"isActive","marks":[{"type":"code"}]},{"type":"text","text":" to "},{"type":"text","text":"predykat typu (type predicate)","marks":[{"type":"bold"}]},{"type":"text","text":": zwraca "},{"type":"text","text":"boolean","marks":[{"type":"code"}]},{"type":"text","text":", ale sygnatura "},{"type":"text","text":"status is ActiveStatus","marks":[{"type":"code"}]},{"type":"text","text":" mówi kompilatorowi, jak zawęzić typ po sprawdzeniu warunku. "},{"type":"text","text":"Extract<OrderStatus, { kind: … }>","marks":[{"type":"code"}]},{"type":"text","text":" wybiera z unii tylko pasujące warianty, więc nie musisz ich przepisywać."}]},{"type":"heading","attrs":{"level":2,"id":"krok-3-zawezanie-typow-narrowing"},"content":[{"type":"text","text":"Krok 3. Zawężanie typów (narrowing)"}]},{"type":"paragraph","content":[{"type":"text","text":"Zawężanie to mechanizm, dzięki któremu kompilator śledzi Twoje "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":"-y. Masz do dyspozycji kilka narzędzi:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"typeof x === \"string\"","marks":[{"type":"code"}]},{"type":"text","text":" – typy prymitywne,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"x instanceof Error","marks":[{"type":"code"}]},{"type":"text","text":" – klasy,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"\"message\" in x","marks":[{"type":"code"}]},{"type":"text","text":" – obecność właściwości (działa też na "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" po sprawdzeniu "},{"type":"text","text":"typeof x === \"object\" && x !== null","marks":[{"type":"code"}]},{"type":"text","text":"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"porównanie z literałem ("},{"type":"text","text":"status.kind === \"cooking\"","marks":[{"type":"code"}]},{"type":"text","text":") – unie dyskryminowane,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"predykaty "},{"type":"text","text":"x is T","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"funkcje asercji","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"asserts x is T","marks":[{"type":"code"}]},{"type":"text","text":" – własne reguły zawężania,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"operator "},{"type":"text","text":"satisfies","marks":[{"type":"code"}]},{"type":"text","text":" – sprawdza zgodność z typem, ale "},{"type":"text","text":"nie poszerza","marks":[{"type":"bold"}]},{"type":"text","text":" typu wartości."}]}]}]},{"type":"codeGroup","attrs":{"title":"Strażnicy typów i 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":" to wzór na każdy blok "},{"type":"text","text":"catch","marks":[{"type":"code"}]},{"type":"text","text":". W TypeScripcie wyrzucić można cokolwiek, nie tylko "},{"type":"text","text":"Error","marks":[{"type":"code"}]},{"type":"text","text":", więc "},{"type":"text","text":"catch (e)","marks":[{"type":"code"}]},{"type":"text","text":" daje "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" i trzeba to zawęzić. "},{"type":"text","text":"assertDefined","marks":[{"type":"code"}]},{"type":"text","text":" zastępuje operator "},{"type":"text","text":"!","marks":[{"type":"code"}]},{"type":"text","text":" – zamiast cichego założenia „na pewno nie jest null” dostajesz czytelny wyjątek w miejscu problemu. "},{"type":"text","text":"satisfies Record<OrderStatusKind, string>","marks":[{"type":"code"}]},{"type":"text","text":" gwarantuje, że każdy status ma kolor. Gdyby dopisać do mapy literówkę "},{"type":"text","text":"\"canceled\"","marks":[{"type":"code"}]},{"type":"text","text":", kompilator zgłosi błąd, a typ obiektu zostaje dokładny."}]},{"type":"heading","attrs":{"level":2,"id":"krok-4-generyki-bez-strachu"},"content":[{"type":"text","text":"Krok 4. Generyki bez strachu"}]},{"type":"paragraph","content":[{"type":"text","text":"Generyk to parametr typu: funkcja lub komponent działa dla wielu typów, nie gubiąc informacji, którego typu użyto. Wywołując generyczną funkcję, prawie nigdy nie podajesz typu w nawiasach ostrych, bo kompilator wywnioskuje go z argumentów."}]},{"type":"codeGroup","attrs":{"title":"Result, groupBy i generyczny komponent"},"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":"Na co zwrócić uwagę:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Ograniczenia (constraints)","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"K extends PropertyKey","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"K extends keyof T","marks":[{"type":"code"}]},{"type":"text","text":" mówią, czego wymagasz od parametru. Dzięki temu "},{"type":"text","text":"pluck(orders, \"customer\")","marks":[{"type":"code"}]},{"type":"text","text":" zwraca "},{"type":"text","text":"string[]","marks":[{"type":"code"}]},{"type":"text","text":", a "},{"type":"text","text":"pluck(orders, \"costomer\")","marks":[{"type":"code"}]},{"type":"text","text":" jest błędem."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Result<T, E>","marks":[{"type":"code"}]},{"type":"text","text":" zamienia wyjątki w wartości. Funkcja "},{"type":"text","text":"getOrders","marks":[{"type":"code"}]},{"type":"text","text":" (krok 6) zwraca "},{"type":"text","text":"Result<…, FetchError>","marks":[{"type":"code"}]},{"type":"text","text":", więc kod, który jej używa, musi obsłużyć błąd – nie da się o nim zapomnieć."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Generyczny komponent ","marks":[{"type":"bold"}]},{"type":"text","text":"Select<T>","marks":[{"type":"code"}]},{"type":"text","text":" przyjmuje opcje i wartość tego samego typu. Zamiast rzutowania "},{"type":"text","text":"e.target.value as T","marks":[{"type":"code"}]},{"type":"text","text":" szuka wybranej opcji na liście, więc typ jest prawdziwy, a nie tylko zadeklarowany."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Nie generyzuj na zapas.","marks":[{"type":"bold"}]},{"type":"text","text":" Jeśli parametr typu występuje w sygnaturze tylko raz, prawie zawsze możesz go usunąć i użyć zwykłego typu."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-5-typy-narzedziowe-utility-types"},"content":[{"type":"text","text":"Krok 5. Typy narzędziowe (utility types)"}]},{"type":"paragraph","content":[{"type":"text","text":"Typy narzędziowe to funkcje na typach: z jednego typu robią inny. Dzięki nim "},{"type":"text","text":"jeden model","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"Order","marks":[{"type":"code"}]},{"type":"text","text":") wystarczy dla formularza, łatki PATCH, listy i statystyk, zamiast czterech ręcznie utrzymywanych kopii."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Typ"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Co robi"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przykład w projekcie"}]}]}]},{"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":"wybiera / usuwa pola"}]}]},{"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":"wszystkie pola opcjonalne / wymagane"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OrderPatch","marks":[{"type":"code"}]},{"type":"text","text":" dla 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":"pola tylko do odczytu"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OrderSummary","marks":[{"type":"code"}]},{"type":"text","text":" w liście"}]}]}]},{"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":"obiekt o kluczach "},{"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":"filtruje unię"}]}]},{"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":"typ wyniku funkcji / obietnicy"}]}]},{"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":"typ mapowany + "},{"type":"text","text":"as","marks":[{"type":"code"}]},{"type":"text","text":" + szablony"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"przekształca klucze"}]}]},{"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":"Ostatnia linijka jest ważna: "},{"type":"text","text":"Awaited<ReturnType<typeof getOrders>>","marks":[{"type":"code"}]},{"type":"text","text":" "},{"type":"text","text":"śledzi kod","marks":[{"type":"bold"}]},{"type":"text","text":". Jeśli zmienisz to, co zwraca "},{"type":"text","text":"getOrders","marks":[{"type":"code"}]},{"type":"text","text":", typ zmieni się razem z nim, a miejsca, które przestały pasować, dostaną błąd kompilacji."}]},{"type":"heading","attrs":{"level":2,"id":"krok-6-typowanie-odpowiedzi-api-z-zod"},"content":[{"type":"text","text":"Krok 6. Typowanie odpowiedzi API z Zod"}]},{"type":"paragraph","content":[{"type":"text","text":"To najważniejszy krok poradnika. "},{"type":"text","text":"Typy TypeScriptu znikają w runtime.","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"const orders = await res.json() as Order[]","marks":[{"type":"code"}]},{"type":"text","text":" niczego nie sprawdza, tylko obiecuje kompilatorowi, że serwer na pewno odesłał to, czego oczekujesz. Gdy backend zmieni format albo zwróci błąd w HTML-u, aplikacja wywróci się trzy komponenty dalej, z komunikatem, który nic nie mówi."}]},{"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/>dla każdego rekordu\"}\n  C -->|\"success\"| D[\"transform:<br/>DTO → Order\"]\n  C -->|\"error\"| E[\"pominięty rekord<br/>+ ostrzeżenie w konsoli\"]\n  D --> F[\"Result.ok({ orders, rejected })\"]\n  A -->|\"sieć / HTTP 5xx\"| G[\"Result.err(FetchError)\"]\n  F --> H[\"Komponenty React<br/>(pełne typy)\"]\n  G --> H","caption":"Granica zaufania: wszystko z zewnątrz jest unknown, dopóki nie przejdzie przez schemat"}},{"type":"paragraph","content":[{"type":"text","text":"Schemat Zod opisuje "},{"type":"text","text":"format przewodowy (wire format)","marks":[{"type":"bold"}]},{"type":"text","text":" – snake_case, ceny w groszach, daty jako stringi ISO – a "},{"type":"text","text":".transform()","marks":[{"type":"code"}]},{"type":"text","text":" mapuje go na model domeny. Typ "},{"type":"text","text":"OrderDto","marks":[{"type":"code"}]},{"type":"text","text":" wyprowadzasz ze schematu przez "},{"type":"text","text":"z.infer","marks":[{"type":"code"}]},{"type":"text","text":", więc schemat i typ nie mogą się rozjechać. Adnotacja "},{"type":"text","text":"(dto): Order","marks":[{"type":"code"}]},{"type":"text","text":" przy "},{"type":"text","text":"transform","marks":[{"type":"code"}]},{"type":"text","text":" sprawia, że kompilator sprawdza wynik mapowania z modelem domeny."}]},{"type":"codeGroup","attrs":{"title":"Dane, schematy i klient API"},"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":"Trzy decyzje projektowe warto przenieść do własnych projektów:"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"fetchJson","marks":[{"type":"code"}]},{"type":"text","text":" jest generyczny względem schematu","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"S extends z.ZodType","marks":[{"type":"code"}]},{"type":"text","text":") i zwraca "},{"type":"text","text":"z.output<S>","marks":[{"type":"code"}]},{"type":"text","text":". Typ wyniku wynika ze schematu, który przekazujesz – nie podajesz go drugi raz."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Walidacja rekord po rekordzie.","marks":[{"type":"bold"}]},{"type":"text","text":" Jeden zepsuty rekord ("},{"type":"text","text":"ord_1045","marks":[{"type":"code"}]},{"type":"text","text":" w danych testowych) nie wygasza całego ekranu. Zostaje pominięty, a liczba odrzuconych rekordów trafia do UI. W panelu administracyjnym to zwykle lepsze niż komunikat „coś poszło nie tak”."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Błędy jako unia","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":"). Komponent wie, co pokazać w każdym przypadku, a wyczerpujący "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" pilnuje, żeby żadnego nie pominąć."}]}]}]},{"type":"prosCons","attrs":{"pros":["zero dodatkowego kodu i kilobajtów w bundlu","wystarcza dla danych, które sam tworzysz w tym samym procesie","błędne dane zatrzymane na granicy, z czytelnym komunikatem (`z.prettifyError`)","typ wyprowadzony ze schematu – jedno źródło prawdy"],"cons":["nie wykrywa zmian formatu po stronie serwera","błąd ujawnia się daleko od przyczyny, często dopiero u użytkownika","dodatkowa zależność (kilkanaście kB) i koszt parsowania dużych odpowiedzi"],"prosTitle":"Same typy (`as`)","consTitle":"Walidacja w runtime (Zod)"}},{"type":"heading","attrs":{"level":2,"id":"krok-7-typescript-w-komponentach-react"},"content":[{"type":"text","text":"Krok 7. TypeScript w komponentach React"}]},{"type":"paragraph","content":[{"type":"text","text":"W React 19 typowanie jest prostsze niż kiedyś: "},{"type":"text","text":"ref","marks":[{"type":"code"}]},{"type":"text","text":" jest zwykłym propem (bez "},{"type":"text","text":"forwardRef","marks":[{"type":"code"}]},{"type":"text","text":"), a "},{"type":"text","text":"React.FC","marks":[{"type":"code"}]},{"type":"text","text":" nie jest potrzebne – wystarczy otypować parametr funkcji. Najważniejsze wzorce:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Props jako typ z przecięciem","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"{ order: Order } & Omit<ComponentProps<\"article\">, \"children\">","marks":[{"type":"code"}]},{"type":"text","text":". Komponent przyjmuje wszystkie natywne atrybuty elementu ("},{"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":") i przekazuje je dalej przez "},{"type":"text","text":"...rest","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Stan jako unia","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"useState<LoadState>","marks":[{"type":"code"}]},{"type":"text","text":" z wariantami "},{"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":". Nie ma kombinacji „ładuje się i jednocześnie ma błąd”, a po "},{"type":"text","text":"if (state.status === \"error\")","marks":[{"type":"code"}]},{"type":"text","text":" masz dostęp do "},{"type":"text","text":"state.error","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Typy zdarzeń","marks":[{"type":"bold"}]},{"type":"text","text":": inline ("},{"type":"text","text":"onChange={(e) => …}","marks":[{"type":"code"}]},{"type":"text","text":") są wnioskowane same. Gdy handler jest zdefiniowany osobno, podaj typ: "},{"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":" dla stałych opcji: literały zostają dokładne ("},{"type":"text","text":"\"cooking\"","marks":[{"type":"code"}]},{"type":"text","text":", a nie "},{"type":"text","text":"string","marks":[{"type":"code"}]},{"type":"text","text":"), a kształt jest sprawdzony."}]}]}]},{"type":"codeGroup","attrs":{"title":"Komponenty i aplikacja"},"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":" przerywa żądanie przez "},{"type":"text","text":"AbortController","marks":[{"type":"code"}]},{"type":"text","text":", gdy komponent znika (albo gdy StrictMode w trybie deweloperskim montuje go dwa razy). W "},{"type":"text","text":"poradniku React","marks":[{"type":"link","attrs":{"href":"/pl/articles/react"}}]},{"type":"text","text":" to samo pobieranie zastąpisz TanStack Query, które obsługuje cache, ponowienia i stany ładowania za Ciebie."}]},{"type":"heading","attrs":{"level":2,"id":"krok-8-ten-sam-kod-w-node-bez-kompilacji"},"content":[{"type":"text","text":"Krok 8. Ten sam kod w Node – bez kompilacji"}]},{"type":"paragraph","content":[{"type":"text","text":"Node 24 (i 22.18+) domyślnie "},{"type":"text","text":"wymazuje typy (type stripping)","marks":[{"type":"bold"}]},{"type":"text","text":": uruchamia plik "},{"type":"text","text":".ts","marks":[{"type":"code"}]},{"type":"text","text":" tak, jakby był JavaScriptem z usuniętymi adnotacjami. Nie ma kroku budowania ani "},{"type":"text","text":"ts-node","marks":[{"type":"code"}]},{"type":"text","text":". Warunek jest jeden: tylko składnia wymazywalna, czyli dokładnie to, czego pilnuje "},{"type":"text","text":"erasableSyntaxOnly","marks":[{"type":"code"}]},{"type":"text","text":". Skrypt używa tych samych schematów i funkcji domeny co aplikacja w przeglądarce:"}]},{"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":"Podział ról jest prosty: "},{"type":"text","text":"Node i Vite uruchamiają kod, ","marks":[{"type":"bold"}]},{"type":"text","text":"tsc","marks":[{"type":"code"}]},{"type":"text","text":" tylko go sprawdza.","marks":[{"type":"bold"}]},{"type":"text","text":" W CI uruchamiasz "},{"type":"text","text":"npm run typecheck","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"tsc -b","marks":[{"type":"code"}]},{"type":"text","text":"), a w edytorze działa serwer językowy TypeScript 7 – szybki nawet w dużych monorepo. Jeśli publikujesz bibliotekę, nadal kompilujesz ją do "},{"type":"text","text":".js","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":".d.ts","marks":[{"type":"code"}]},{"type":"text","text":", ale aplikacje i skrypty tego nie potrzebują."}]},{"type":"heading","attrs":{"level":2,"id":"typowe-pulapki"},"content":[{"type":"text","text":"Typowe pułapki"}]},{"type":"paragraph","content":[{"type":"text","text":"Najgroźniejsze błędy w TypeScripcie to te, które "},{"type":"text","text":"się kompilują","marks":[{"type":"bold"}]},{"type":"text","text":". Każdy fragment poniżej przechodzi "},{"type":"text","text":"tsc","marks":[{"type":"code"}]},{"type":"text","text":" bez ostrzeżeń, a w runtime kończy się błędem albo cichym "},{"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":"Typowy błąd: `as` na odpowiedzi z API"},"content":[{"type":"paragraph","content":[{"type":"text","text":"await res.json() as Order[]","marks":[{"type":"code"}]},{"type":"text","text":" to najczęstsza przyczyna błędów „undefined is not a function” w aplikacjach napisanych w TypeScripcie. Rzutowanie nie konwertuje ani nie sprawdza danych – wyłącza tylko kontrolę kompilatora. Dane z sieci, "},{"type":"text","text":"localStorage","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"postMessage","marks":[{"type":"code"}]},{"type":"text","text":" czy parametrów URL zawsze traktuj jako "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" i przepuszczaj przez schemat."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Kilka mniej oczywistych zasad:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"any","marks":[{"type":"code"}]},{"type":"text","text":" zostaw w kodzie migracyjnym","marks":[{"type":"bold"}]},{"type":"text","text":" i oznacz komentarzem z zadaniem do zrobienia. W nowym kodzie używaj "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" – wymusza zawężenie."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Unia literałów zamiast ","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":" nie generuje kodu, działa z "},{"type":"text","text":"erasableSyntaxOnly","marks":[{"type":"code"}]},{"type":"text","text":" i daje się iterować przez tablicę "},{"type":"text","text":"as const","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Object.keys()","marks":[{"type":"code"}]},{"type":"text","text":" zwraca ","marks":[{"type":"bold"}]},{"type":"text","text":"string[]","marks":[{"type":"code"}]},{"type":"text","text":" celowo","marks":[{"type":"bold"}]},{"type":"text","text":" – obiekt może mieć w runtime więcej kluczy, niż mówi typ. Rzutuj tylko wtedy, gdy sam tworzysz obiekt."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"// @ts-ignore","marks":[{"type":"code"}]},{"type":"text","text":" zamieniaj na ","marks":[{"type":"bold"}]},{"type":"text","text":"// @ts-expect-error","marks":[{"type":"code"}]},{"type":"text","text":" – ten drugi zgłosi błąd, gdy problem zniknie, więc nie zostanie w kodzie na zawsze."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"sciaga-kiedy-czego-uzyc"},"content":[{"type":"text","text":"Ściąga: kiedy czego użyć"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Sytuacja"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Narzędzie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Obiekt, który ktoś rozszerza (props, kontrakt)"}]}]},{"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":"Kilka wykluczających się stanów"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"unia dyskryminowana + "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" z "},{"type":"text","text":"assertNever","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Dane z sieci, plików, formularzy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" + schemat Zod, typ przez "},{"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":"Stała konfiguracja, mapa kolorów, opcje"}]}]},{"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":"Identyfikatory, których nie wolno mylić"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"typy z markerem (branded types)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Funkcja działająca dla wielu typów"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"generyk z ograniczeniem ("},{"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":"Wariant istniejącego modelu (formularz, 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":" zamiast kopii"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"sprawdz-sie"},"content":[{"type":"text","text":"Sprawdź się"}]},{"type":"quiz","attrs":{"question":"Dodajesz do `OrderStatus` nowy wariant `{ kind: \"refunded\"; amountCents: number }`. Co się stanie z funkcją `describeStatus`?","multiple":false,"options":[{"text":"Nic – zwróci `undefined` dla nowego statusu","correct":false,"explanation":"Tak byłoby bez gałęzi `default` z `assertNever`. W tym projekcie kompilator zgłosi błąd."},{"text":"Projekt przestanie się kompilować w linii `assertNever(status)`","correct":true,"explanation":"Tak. W gałęzi `default` zostaje typ `{ kind: \"refunded\" … }`, którego nie da się przypisać do `never`."},{"text":"TypeScript doda brakujący `case` automatycznie","correct":false,"explanation":"Kompilator niczego nie dopisuje – tylko wskazuje miejsce, które trzeba uzupełnić."}]}},{"type":"quiz","attrs":{"question":"Który zapis najlepiej typuje odpowiedź z `fetch`?","multiple":false,"options":[{"text":"`const data = (await res.json()) as Order[]`","correct":false,"explanation":"Rzutowanie niczego nie sprawdza. Gdy serwer zmieni format, błąd wyjdzie daleko od przyczyny."},{"text":"`const data: any = await res.json()`","correct":false,"explanation":"`any` wyłącza kontrolę typów we wszystkim, czego dotknie."},{"text":"`const data = OrderListSchema.parse(await res.json())`","correct":true,"explanation":"Tak. Schemat waliduje dane w runtime, a typ wyniku jest z niego wyprowadzony."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Pytanie rekrutacyjne: czym różni się "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" od "},{"type":"text","text":"any","marks":[{"type":"code"}]},{"type":"text","text":" i kiedy używać "},{"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":" wyłącza sprawdzanie typów: wartość można przypisać wszędzie i wywołać na niej cokolwiek, a „zaraża” wszystko, czego dotknie. "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" to bezpieczny odpowiednik – można do niego przypisać wszystko, ale zanim go użyjesz, musisz zawęzić typ ("},{"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":", schemat). Dlatego "},{"type":"text","text":"unknown","marks":[{"type":"code"}]},{"type":"text","text":" to właściwy typ dla danych z zewnątrz i dla "},{"type":"text","text":"catch (e)","marks":[{"type":"code"}]},{"type":"text","text":". "},{"type":"text","text":"never","marks":[{"type":"code"}]},{"type":"text","text":" to typ bez wartości: zwracają go funkcje, które zawsze rzucają wyjątek, i zostaje w gałęzi "},{"type":"text","text":"default","marks":[{"type":"code"}]},{"type":"text","text":" wyczerpującego "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":". Przypisanie czegokolwiek do "},{"type":"text","text":"never","marks":[{"type":"code"}]},{"type":"text","text":" jest błędem, dlatego "},{"type":"text","text":"assertNever(x: never)","marks":[{"type":"code"}]},{"type":"text","text":" zamienia nieobsłużony wariant unii w błąd kompilacji."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"co-dalej"},"content":[{"type":"text","text":"Co dalej"}]},{"type":"linkCard","attrs":{"url":"/pl/topics/react","title":"React","description":"Komponenty, hooki, TanStack Query i formularze z react-hook-form + Zod","kind":"topic","ref":"react"}},{"type":"linkCard","attrs":{"url":"/pl/topics/state","title":"Stan (State)","description":"Kiedy unia dyskryminowana wystarczy, a kiedy potrzebny jest wzorzec Stan","kind":"topic","ref":"state"}},{"type":"linkCard","attrs":{"url":"/pl/topics/adapter","title":"Adapter","description":"Mapowanie DTO → model domeny to adapter na granicy systemu","kind":"topic","ref":"adapter"}},{"type":"linkCard","attrs":{"url":"/pl/topics/mui","title":"MUI","description":"Typowany motyw i własne warianty komponentów Material UI","kind":"topic","ref":"mui"}}]},"toc":[{"id":"krok-0-projekt-i-tsconfig-ktory-naprawde-pilnuje","text":"Krok 0. Projekt i tsconfig, który naprawdę pilnuje","level":2,"locked":false},{"id":"krok-1-typy-czy-interfejsy","text":"Krok 1. Typy czy interfejsy?","level":2,"locked":false},{"id":"krok-2-unie-dyskryminowane-i-wyczerpujacy-switch","text":"Krok 2. Unie dyskryminowane i wyczerpujący switch","level":2,"locked":false},{"id":"krok-3-zawezanie-typow-narrowing","text":"Krok 3. Zawężanie typów (narrowing)","level":2,"locked":false},{"id":"krok-4-generyki-bez-strachu","text":"Krok 4. Generyki bez strachu","level":2,"locked":false},{"id":"krok-5-typy-narzedziowe-utility-types","text":"Krok 5. Typy narzędziowe (utility types)","level":2,"locked":false},{"id":"krok-6-typowanie-odpowiedzi-api-z-zod","text":"Krok 6. Typowanie odpowiedzi API z Zod","level":2,"locked":false},{"id":"krok-7-typescript-w-komponentach-react","text":"Krok 7. TypeScript w komponentach React","level":2,"locked":false},{"id":"krok-8-ten-sam-kod-w-node-bez-kompilacji","text":"Krok 8. Ten sam kod w Node – bez kompilacji","level":2,"locked":false},{"id":"typowe-pulapki","text":"Typowe pułapki","level":2,"locked":false},{"id":"sciaga-kiedy-czego-uzyc","text":"Ściąga: kiedy czego użyć","level":2,"locked":false},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":false},{"id":"co-dalej","text":"Co dalej","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":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}