English

Poradnik · TypeScript · React

TypeScript dla programistów React i Node – od typów do bezpiecznego API

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.

Autor · · 25 min czytania

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 a interface po walidację JSON-a z serwera.

Wymagania wstępne: Node.js 24 (albo 22.18+), podstawy JavaScriptu (ES2015+, async/await, moduły) i Reacta (komponent, props, useState). Nie musisz znać wcześniejszych wersji TypeScriptu.

7.0
wersja TypeScript – natywny kompilator napisany w Go
8–12×
szybsze pełne buildy – według zespołu TypeScript
strict
domyślnie od 6.0 – nie musisz już włączać ręcznie
0
`any` w kodzie aplikacji – `unknown` + schemat zamiast zgadywania

Krok 0. Projekt i tsconfig, który naprawdę pilnuje

Zacznij od szablonu Vite – generuje dwa pliki konfiguracji: jeden dla kodu w przeglądarce, drugi dla plików uruchamianych przez Node (konfiguracja Vite, skrypty).

npm create vite@latest pierogi-ts -- --template react-ts
cd pierogi-ts
npm install zod
npm run dev

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ą:

OpcjaTeraz (6.0/7.0)Co to znaczy w praktyce
stricttrue domyślnienull/undefined i niejawne any są błędami od pierwszego dnia
types[] domyślnieglobalne typy (process, describe) trzeba wskazać jawnie, np. "types": ["node"]
module / targetesnext / najnowszy ESkoniec z kompilacją do ES5 – najniższy cel to ES2015
baseUrl, moduleResolution: "node"usunięte w 7.0używaj bundler (Vite) albo nodenext (Node) i aliasów przez paths
esModuleInterop: falseniedozwolonedomyślny import z pakietów CommonJS po prostu działa

Oto konfiguracja projektu. Do ustawień z szablonu dodaliśmy noUncheckedIndexedAccess (indeks tablicy lub rekordu może zwrócić undefined) i noImplicitOverride:

Konfiguracja projektu

package.json
{
  "name": "pierogi-ts",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "typecheck": "tsc -b",
    "check:orders": "node scripts/check-orders.ts"
  },
  "dependencies": {
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/node": "^24.0.0",
    "@types/react": "^19.3.0",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "files": [],
  "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}
tsconfig.app.json
{
  "compilerOptions": {
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client"],
    "jsx": "react-jsx",
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "moduleDetection": "force",
    "skipLibCheck": true,

    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "include": ["src"]
}
tsconfig.node.json
{
  "compilerOptions": {
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
    "target": "es2023",
    "lib": ["ES2023"],
    "module": "nodenext",
    "types": ["node"],
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["vite.config.ts", "scripts", "examples"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [react()],
});
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogi TS</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

Na kilka flag warto zwrócić uwagę:

  • verbatimModuleSyntax – importy używane tylko jako typy muszą mieć import type. Dzięki temu narzędzia, które tylko wymazują typy (Vite, Node), nie muszą zgadywać, co usunąć.
  • erasableSyntaxOnly – zakazuje konstrukcji generujących kod w runtime: enum, namespace z wartościami i właściwości w parametrach konstruktora (constructor(private x: number)). Zamiast enum używasz unii literałów.
  • allowImportingTsExtensions – importujesz ./App.tsx, a nie ./App. Tak samo zapisany import zrozumie Vite i Node.
  • noUncheckedIndexedAccess – orders[0] ma typ Order | undefined. Na początku bywa to irytujące, ale łapie prawdziwe błędy z pustymi listami.

Krok 1. Typy czy interfejsy?

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:

interfacetype
Kształt obiektutaktak
Unie, krotki, typy prymitywnenietak ("vegan" | "spicy", [number, number])
Typy mapowane i warunkowenietak (Record<…>, Pick<…>, T extends U ? …)
Rozszerzanieextends, czytelne błędy& (przecięcie), błędy bywają mniej czytelne
Łączenie deklaracji (declaration merging)tak – dwie deklaracje o tej samej nazwie się sumująnie – duplikat to błąd

Praktyczna zasada, która sprawdza się w zespołach: interface dla kształtów obiektów, które ktoś rozszerza (kontrakty, props, modele), type dla wszystkiego, co jest unią albo powstaje z innych typów. Najważniejsze jest to, żeby zespół trzymał się jednej konwencji.

Model domeny pierogarni pokazuje oba zapisy. Zwróć uwagę na typy z markerem (branded types) – OrderId i MenuItemId to w runtime zwykłe stringi, ale kompilator nie pozwoli przekazać jednego w miejsce drugiego:

src/domain/order.ts
// Type aliases: unions, brands and anything computed from other types.
export type Tag = "vegan" | "spicy" | "new";
export type Filling = "potato-cheese" | "meat" | "cabbage-mushroom";

// Branded ids: both are strings at runtime, but they cannot be mixed up at compile time.
export type OrderId = string & { readonly __brand: "OrderId" };
export type MenuItemId = string & { readonly __brand: "MenuItemId" };

// Interfaces: object shapes that other shapes extend (public contracts).
export interface MenuItem {
  readonly id: MenuItemId;
  name: string;
  priceCents: number;
  tags: readonly Tag[];
}

export interface DumplingItem extends MenuItem {
  filling: Filling;
  pieces: 6 | 10 | 20;
}

export interface OrderLine {
  itemId: MenuItemId;
  name: string;
  quantity: number;
  unitPriceCents: number;
}

// Discriminated union: `kind` tells TypeScript which fields exist.
export type OrderStatus =
  | { kind: "placed"; placedAt: Date }
  | { kind: "cooking"; etaMinutes: number }
  | { kind: "delivering"; courier: string; etaMinutes: number }
  | { kind: "delivered"; deliveredAt: Date }
  | { kind: "cancelled"; reason: string };

export type OrderStatusKind = OrderStatus["kind"]; // "placed" | "cooking" | ...

export interface Order {
  id: OrderId;
  customer: string;
  lines: OrderLine[];
  status: OrderStatus;
  note?: string;
}

// The only place where a raw string becomes a branded id.
export const toOrderId = (raw: string): OrderId => raw as OrderId;
export const toMenuItemId = (raw: string): MenuItemId => raw as MenuItemId;

Ten marker (__brand) istnieje tylko w systemie typów. Jedynym miejscem, gdzie zwykły string staje się OrderId, są funkcje toOrderId i toMenuItemId. Wywołasz je w warstwie, która waliduje dane z API, i nigdzie indziej.

Krok 2. Unie dyskryminowane i wyczerpujący switch

Klasyczny błąd modelowania to jeden obiekt z polami opcjonalnymi: status: string; courier?: string; etaMinutes?: number; reason?: string. Taki typ pozwala zapisać zamówienie „anulowane, z kurierem w drodze i bez powodu anulowania”. Unia dyskryminowana (discriminated union) opisuje każdy stan osobno, a wspólne pole kind mówi kompilatorowi, który wariant właśnie obsługujesz.

Diagram: Zamówienie jako maszyna stanów – każdy stan ma tylko swoje pola

Wewnątrz case "delivering" TypeScript wie, że istnieje status.courier. W gałęzi default zostaje typ never. Jeśli ktoś doda status "refunded" i zapomni go obsłużyć, wywołanie assertNever(status) przestanie się kompilować:

src/domain/status.ts
import type { Order, OrderStatus } from "./order.ts";

export function assertNever(value: never): never {
  throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}

// Exhaustive switch: add a new status kind and this function stops compiling.
export function describeStatus(status: OrderStatus): string {
  switch (status.kind) {
    case "placed":
      return `Placed at ${status.placedAt.toLocaleTimeString()}`;
    case "cooking":
      return `In the kitchen, ready in ~${status.etaMinutes} min`;
    case "delivering":
      return `${status.courier} is on the way (${status.etaMinutes} min)`;
    case "delivered":
      return `Delivered at ${status.deliveredAt.toLocaleTimeString()}`;
    case "cancelled":
      return `Cancelled: ${status.reason}`;
    default:
      return assertNever(status);
  }
}

// Extract<> picks union members by their discriminant.
export type ActiveStatus = Extract<OrderStatus, { kind: "cooking" | "delivering" }>;

// Type predicate: after `if (isActive(o.status))` the status is ActiveStatus.
export function isActive(status: OrderStatus): status is ActiveStatus {
  return status.kind === "cooking" || status.kind === "delivering";
}

export function totalCents(order: Pick<Order, "lines">): number {
  return order.lines.reduce((sum, line) => sum + line.quantity * line.unitPriceCents, 0);
}

Funkcja isActive to predykat typu (type predicate): zwraca boolean, ale sygnatura status is ActiveStatus mówi kompilatorowi, jak zawęzić typ po sprawdzeniu warunku. Extract<OrderStatus, { kind: … }> wybiera z unii tylko pasujące warianty, więc nie musisz ich przepisywać.

Krok 3. Zawężanie typów (narrowing)

Zawężanie to mechanizm, dzięki któremu kompilator śledzi Twoje if-y. Masz do dyspozycji kilka narzędzi:

  • typeof x === "string" – typy prymitywne,
  • x instanceof Error – klasy,
  • "message" in x – obecność właściwości (działa też na unknown po sprawdzeniu typeof x === "object" && x !== null),
  • porównanie z literałem (status.kind === "cooking") – unie dyskryminowane,
  • predykaty x is T i funkcje asercji asserts x is T – własne reguły zawężania,
  • operator satisfies – sprawdza zgodność z typem, ale nie poszerza typu wartości.

Strażnicy typów i satisfies

src/lib/guards.ts
// typeof, instanceof and `in` narrow `unknown` step by step – no casts needed.
export function errorMessage(error: unknown): string {
  if (error instanceof Error) return error.message;
  if (typeof error === "string") return error;
  if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
    return error.message;
  }
  return "Unknown error";
}

// Assertion function: after the call TypeScript knows the value is not null/undefined.
export function assertDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
  if (value === undefined || value === null) throw new Error(`${name} is missing`);
}

// Union parameter narrowed with typeof.
export function formatPrice(amount: number | string, currency = "PLN"): string {
  const cents = typeof amount === "string" ? Math.round(Number.parseFloat(amount) * 100) : amount;
  return new Intl.NumberFormat("pl-PL", { style: "currency", currency }).format(cents / 100);
}
src/components/statusColors.ts
import type { OrderStatusKind } from "../domain/order.ts";

// `satisfies` checks the shape (every kind has a colour) but keeps the literal types.
export const statusColors = {
  placed: "#1c7ed6",
  cooking: "#e8590c",
  delivering: "#7048e8",
  delivered: "#2b8a3e",
  cancelled: "#868e96",
} satisfies Record<OrderStatusKind, string>;

errorMessage(error: unknown) to wzór na każdy blok catch. W TypeScripcie wyrzucić można cokolwiek, nie tylko Error, więc catch (e) daje unknown i trzeba to zawęzić. assertDefined zastępuje operator ! – zamiast cichego założenia „na pewno nie jest null” dostajesz czytelny wyjątek w miejscu problemu. satisfies Record<OrderStatusKind, string> gwarantuje, że każdy status ma kolor. Gdyby dopisać do mapy literówkę "canceled", kompilator zgłosi błąd, a typ obiektu zostaje dokładny.

Krok 4. Generyki bez strachu

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.

Result, groupBy i generyczny komponent

src/lib/result.ts
// A generic Result: errors become part of the return type instead of hidden exceptions.
export type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };

export const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
export const err = <E>(error: E): Result<never, E> => ({ ok: false, error });

// K extends PropertyKey: the key function must return something usable as an object key.
export function groupBy<T, K extends PropertyKey>(items: readonly T[], keyOf: (item: T) => K): Partial<Record<K, T[]>> {
  const groups: Partial<Record<K, T[]>> = {};
  for (const item of items) {
    (groups[keyOf(item)] ??= []).push(item);
  }
  return groups;
}

// K extends keyof T: only existing property names are accepted, and the result type follows.
export function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}
src/components/Select.tsx
// Generic component: T is inferred from `value` and `options` at the call site.
interface SelectProps<T extends string> {
  label: string;
  value: T;
  options: readonly { value: T; label: string }[];
  onChange: (value: T) => void;
}

export function Select<T extends string>({ label, value, options, onChange }: SelectProps<T>) {
  return (
    <label style={{ display: "inline-flex", gap: 8, alignItems: "center" }}>
      {label}
      <select
        value={value}
        onChange={(e) => {
          // Narrow the DOM string back to T instead of casting with `as T`.
          const next = options.find((o) => o.value === e.target.value);
          if (next) onChange(next.value);
        }}
      >
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </label>
  );
}

Na co zwrócić uwagę:

  • Ograniczenia (constraints) – K extends PropertyKey i K extends keyof T mówią, czego wymagasz od parametru. Dzięki temu pluck(orders, "customer") zwraca string[], a pluck(orders, "costomer") jest błędem.
  • Result<T, E> zamienia wyjątki w wartości. Funkcja getOrders (krok 6) zwraca Result<…, FetchError>, więc kod, który jej używa, musi obsłużyć błąd – nie da się o nim zapomnieć.
  • Generyczny komponent Select<T> przyjmuje opcje i wartość tego samego typu. Zamiast rzutowania e.target.value as T szuka wybranej opcji na liście, więc typ jest prawdziwy, a nie tylko zadeklarowany.
  • Nie generyzuj na zapas. Jeśli parametr typu występuje w sygnaturze tylko raz, prawie zawsze możesz go usunąć i użyć zwykłego typu.

Krok 5. Typy narzędziowe (utility types)

Typy narzędziowe to funkcje na typach: z jednego typu robią inny. Dzięki nim jeden model (Order) wystarczy dla formularza, łatki PATCH, listy i statystyk, zamiast czterech ręcznie utrzymywanych kopii.

TypCo robiPrzykład w projekcie
Pick<T, K> / Omit<T, K>wybiera / usuwa polaOrderDraft = Omit<Order, "id" | "status">
Partial<T> / Required<T>wszystkie pola opcjonalne / wymaganeOrderPatch dla PATCH
Readonly<T>pola tylko do odczytuOrderSummary w liście
Record<K, V>obiekt o kluczach KStatusCounts, statusColors
Extract<T, U> / Exclude<T, U>filtruje unięActiveStatus
ReturnType<F> / Awaited<T>typ wyniku funkcji / obietnicyOrdersResult
typ mapowany + as + szablonyprzekształca kluczeStatusHandlers → onPlaced, onCooking…
src/lib/types.ts
import type { getOrders } from "../api/client.ts";
import type { Order, OrderStatus } from "../domain/order.ts";

// What the checkout form produces: the server assigns id and status.
export type OrderDraft = Omit<Order, "id" | "status">;

// Body of PATCH /orders/:id – every field optional, only these two editable.
export type OrderPatch = Partial<Pick<Order, "customer" | "note">>;

// A read-only projection for lists.
export type OrderSummary = Readonly<Pick<Order, "id" | "customer">> & { totalCents: number };

// One counter per status kind – adding a kind forces you to handle it here.
export type StatusCounts = Record<OrderStatus["kind"], number>;

// Mapped type with key remapping and template literal types:
// { onPlaced?: (s: {kind:"placed"...}) => void; onCooking?: ...; ... }
export type StatusHandlers = {
  [S in OrderStatus as `on${Capitalize<S["kind"]>}`]?: (status: S) => void;
};

// Types computed from code: follow the function, never copy its result type by hand.
export type OrdersResult = Awaited<ReturnType<typeof getOrders>>;

Ostatnia linijka jest ważna: Awaited<ReturnType<typeof getOrders>> śledzi kod. Jeśli zmienisz to, co zwraca getOrders, typ zmieni się razem z nim, a miejsca, które przestały pasować, dostaną błąd kompilacji.

Krok 6. Typowanie odpowiedzi API z Zod

To najważniejszy krok poradnika. Typy TypeScriptu znikają w runtime. const orders = await res.json() as Order[] 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.

Diagram: Granica zaufania: wszystko z zewnątrz jest unknown, dopóki nie przejdzie przez schemat

Schemat Zod opisuje format przewodowy (wire format) – snake_case, ceny w groszach, daty jako stringi ISO – a .transform() mapuje go na model domeny. Typ OrderDto wyprowadzasz ze schematu przez z.infer, więc schemat i typ nie mogą się rozjechać. Adnotacja (dto): Order przy transform sprawia, że kompilator sprawdza wynik mapowania z modelem domeny.

Dane, schematy i klient API

public/orders.json
[
  {
    "id": "ord_1042",
    "customer": "Halina K.",
    "lines": [{ "item_id": "ruskie-10", "name": "Ruskie (10 pcs)", "quantity": 2, "unit_price": 3200 }],
    "status": { "type": "delivering", "courier": "Zdzisław", "eta_minutes": 12 },
    "note": "Extra fried onion"
  },
  {
    "id": "ord_1043",
    "customer": "Marek W.",
    "lines": [
      { "item_id": "meat-6", "name": "Meat (6 pcs)", "quantity": 1, "unit_price": 2400 },
      { "item_id": "cabbage-10", "name": "Cabbage & mushroom (10 pcs)", "quantity": 1, "unit_price": 3400 }
    ],
    "status": { "type": "cooking", "eta_minutes": 18 }
  },
  {
    "id": "ord_1044",
    "customer": "Ola P.",
    "lines": [{ "item_id": "ruskie-20", "name": "Ruskie (20 pcs)", "quantity": 1, "unit_price": 5900 }],
    "status": { "type": "delivered", "delivered_at": "2026-11-27T12:41:00Z" }
  },
  {
    "id": "ord_1045",
    "customer": "",
    "lines": [],
    "status": { "type": "teleported" }
  }
]
src/api/schemas.ts
import { z } from "zod";
import { toMenuItemId, toOrderId, type Order, type OrderStatus } from "../domain/order.ts";

// Wire format: snake_case, prices in grosze, dates as ISO strings.
const StatusDtoSchema = z.discriminatedUnion("type", [
  z.object({ type: z.literal("placed"), placed_at: z.iso.datetime() }),
  z.object({ type: z.literal("cooking"), eta_minutes: z.int().nonnegative() }),
  z.object({ type: z.literal("delivering"), courier: z.string().min(1), eta_minutes: z.int().nonnegative() }),
  z.object({ type: z.literal("delivered"), delivered_at: z.iso.datetime() }),
  z.object({ type: z.literal("cancelled"), reason: z.string() }),
]);

const OrderLineDtoSchema = z.object({
  item_id: z.string().min(1),
  name: z.string().min(1),
  quantity: z.int().positive(),
  unit_price: z.int().nonnegative(),
});

export const OrderDtoSchema = z.object({
  id: z.string().regex(/^ord_\d+$/, "Expected an id like ord_123"),
  customer: z.string().min(1),
  lines: z.array(OrderLineDtoSchema).min(1),
  status: StatusDtoSchema,
  note: z.string().max(200).optional(),
});

// The DTO type is derived from the schema – one source of truth, no drift.
export type OrderDto = z.infer<typeof OrderDtoSchema>;

function toStatus(dto: OrderDto["status"]): OrderStatus {
  switch (dto.type) {
    case "placed":
      return { kind: "placed", placedAt: new Date(dto.placed_at) };
    case "cooking":
      return { kind: "cooking", etaMinutes: dto.eta_minutes };
    case "delivering":
      return { kind: "delivering", courier: dto.courier, etaMinutes: dto.eta_minutes };
    case "delivered":
      return { kind: "delivered", deliveredAt: new Date(dto.delivered_at) };
    case "cancelled":
      return { kind: "cancelled", reason: dto.reason };
  }
}

// Validate the DTO and map it to the domain model in one step.
export const OrderSchema = OrderDtoSchema.transform(
  (dto): Order => ({
    id: toOrderId(dto.id),
    customer: dto.customer,
    lines: dto.lines.map((l) => ({
      itemId: toMenuItemId(l.item_id),
      name: l.name,
      quantity: l.quantity,
      unitPriceCents: l.unit_price,
    })),
    status: toStatus(dto.status),
    note: dto.note,
  }),
);
src/api/client.ts
import { z } from "zod";
import type { Order } from "../domain/order.ts";
import { errorMessage } from "../lib/guards.ts";
import { err, ok, type Result } from "../lib/result.ts";
import { OrderSchema } from "./schemas.ts";

export type FetchError =
  | { type: "network"; message: string }
  | { type: "http"; status: number; message: string }
  | { type: "invalid-data"; details: string };

// Generic over the schema: the return type is whatever the schema outputs.
export async function fetchJson<S extends z.ZodType>(
  url: string,
  schema: S,
  init?: RequestInit,
): Promise<Result<z.output<S>, FetchError>> {
  let response: Response;
  try {
    response = await fetch(url, init);
  } catch (e) {
    return err({ type: "network", message: errorMessage(e) });
  }
  if (!response.ok) return err({ type: "http", status: response.status, message: response.statusText });

  const json: unknown = await response.json(); // unknown, not any: you must validate before use
  const parsed = schema.safeParse(json);
  return parsed.success ? ok(parsed.data) : err({ type: "invalid-data", details: z.prettifyError(parsed.error) });
}

// One broken record should not blank the whole screen: validate item by item.
export async function getOrders(signal?: AbortSignal): Promise<Result<{ orders: Order[]; rejected: number }, FetchError>> {
  const res = await fetchJson("/orders.json", z.array(z.unknown()), { signal: signal ?? null });
  if (!res.ok) return res;

  const orders: Order[] = [];
  let rejected = 0;
  for (const raw of res.value) {
    const parsed = OrderSchema.safeParse(raw);
    if (parsed.success) orders.push(parsed.data);
    else {
      rejected++;
      console.warn("Skipping invalid order:\n" + z.prettifyError(parsed.error));
    }
  }
  return ok({ orders, rejected });
}

Trzy decyzje projektowe warto przenieść do własnych projektów:

  1. fetchJson jest generyczny względem schematu (S extends z.ZodType) i zwraca z.output<S>. Typ wyniku wynika ze schematu, który przekazujesz – nie podajesz go drugi raz.
  2. Walidacja rekord po rekordzie. Jeden zepsuty rekord (ord_1045 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”.
  3. Błędy jako unia FetchError (network / http / invalid-data). Komponent wie, co pokazać w każdym przypadku, a wyczerpujący switch pilnuje, żeby żadnego nie pominąć.

Same typy (`as`)

  • 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

Walidacja w runtime (Zod)

  • 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

Krok 7. TypeScript w komponentach React

W React 19 typowanie jest prostsze niż kiedyś: ref jest zwykłym propem (bez forwardRef), a React.FC nie jest potrzebne – wystarczy otypować parametr funkcji. Najważniejsze wzorce:

  • Props jako typ z przecięciem: { order: Order } & Omit<ComponentProps<"article">, "children">. Komponent przyjmuje wszystkie natywne atrybuty elementu (className, aria-*, data-*) i przekazuje je dalej przez ...rest.
  • Stan jako unia: useState<LoadState> z wariantami loading / error / ready. Nie ma kombinacji „ładuje się i jednocześnie ma błąd”, a po if (state.status === "error") masz dostęp do state.error.
  • Typy zdarzeń: inline (onChange={(e) => …}) są wnioskowane same. Gdy handler jest zdefiniowany osobno, podaj typ: ChangeEvent<HTMLInputElement>.
  • as const satisfies dla stałych opcji: literały zostają dokładne ("cooking", a nie string), a kształt jest sprawdzony.

Komponenty i aplikacja

src/components/OrderCard.tsx
import type { ComponentProps } from "react";
import type { Order, OrderId } from "../domain/order.ts";
import { describeStatus, isActive, totalCents } from "../domain/status.ts";
import { formatPrice } from "../lib/guards.ts";
import { statusColors } from "./statusColors.ts";

// Own props + every native <article> prop except children (we render our own).
type OrderCardProps = {
  order: Order;
  onCancel?: (id: OrderId) => void;
} & Omit<ComponentProps<"article">, "children">;

export function OrderCard({ order, onCancel, style, ...rest }: OrderCardProps) {
  const { status } = order;
  return (
    <article
      {...rest}
      style={{ border: "1px solid #dee2e6", borderRadius: 8, padding: 12, opacity: status.kind === "cancelled" ? 0.6 : 1, ...style }}
    >
      <header>
        <strong>{order.customer}</strong> · {formatPrice(totalCents(order))}
      </header>
      <p style={{ color: statusColors[status.kind], margin: "6px 0" }}>{describeStatus(status)}</p>
      {order.note && <p style={{ margin: 0 }}><em>{order.note}</em></p>}
      {/* isActive() is a type predicate – inside, status is "cooking" | "delivering" */}
      {isActive(status) && onCancel && (
        <button type="button" onClick={() => onCancel(order.id)}>
          Cancel ({status.etaMinutes} min left)
        </button>
      )}
    </article>
  );
}
src/App.tsx
import { useEffect, useMemo, useState, type ChangeEvent } from "react";
import { getOrders, type FetchError } from "./api/client.ts";
import { OrderCard } from "./components/OrderCard.tsx";
import { Select } from "./components/Select.tsx";
import type { Order, OrderId, OrderStatusKind } from "./domain/order.ts";
import { groupBy } from "./lib/result.ts";

// UI state as a discriminated union: no "loading + error + data" combinations that make no sense.
type LoadState =
  | { status: "loading" }
  | { status: "error"; error: FetchError }
  | { status: "ready"; orders: Order[]; rejected: number };

type StatusFilter = OrderStatusKind | "all";

const filterOptions = [
  { value: "all", label: "All" },
  { value: "placed", label: "Placed" },
  { value: "cooking", label: "Cooking" },
  { value: "delivering", label: "Delivering" },
  { value: "delivered", label: "Delivered" },
  { value: "cancelled", label: "Cancelled" },
] as const satisfies readonly { value: StatusFilter; label: string }[];

function errorText(error: FetchError): string {
  switch (error.type) {
    case "network":
      return `No connection: ${error.message}`;
    case "http":
      return `Server error ${error.status}`;
    case "invalid-data":
      return "The server sent data we do not understand";
  }
}

export default function App() {
  const [state, setState] = useState<LoadState>({ status: "loading" });
  const [filter, setFilter] = useState<StatusFilter>("all");
  const [query, setQuery] = useState("");

  useEffect(() => {
    const controller = new AbortController();
    getOrders(controller.signal).then((res) => {
      if (controller.signal.aborted) return;
      setState(res.ok ? { status: "ready", ...res.value } : { status: "error", error: res.error });
    });
    return () => controller.abort();
  }, []);

  const orders = state.status === "ready" ? state.orders : [];
  const visible = useMemo(
    () =>
      orders.filter(
        (o) => (filter === "all" || o.status.kind === filter) && o.customer.toLowerCase().includes(query.toLowerCase()),
      ),
    [orders, filter, query],
  );
  const counts = groupBy(orders, (o) => o.status.kind);

  // Explicit event type when the handler is declared outside JSX.
  const handleQuery = (e: ChangeEvent<HTMLInputElement>) => setQuery(e.target.value);

  const cancel = (id: OrderId) =>
    setState((s) =>
      s.status !== "ready"
        ? s
        : {
            ...s,
            orders: s.orders.map((o) =>
              o.id === id ? { ...o, status: { kind: "cancelled", reason: "Cancelled by the customer" } } : o,
            ),
          },
    );

  if (state.status === "loading") return <p>Loading orders…</p>;
  if (state.status === "error") return <p role="alert">{errorText(state.error)}</p>;

  return (
    <main style={{ fontFamily: "system-ui", maxWidth: 640, margin: "24px auto", display: "grid", gap: 12 }}>
      <h1>Orders</h1>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
        <Select label="Status" value={filter} options={filterOptions} onChange={setFilter} />
        <input placeholder="Customer…" value={query} onChange={handleQuery} />
      </div>
      <small>
        In the kitchen: {counts.cooking?.length ?? 0} · On the way: {counts.delivering?.length ?? 0}
        {state.rejected > 0 && ` · ${state.rejected} invalid record(s) skipped`}
      </small>
      {visible.map((order) => (
        <OrderCard key={order.id} order={order} onCancel={cancel} />
      ))}
    </main>
  );
}
src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import { assertDefined } from "./lib/guards.ts";

const container = document.getElementById("root");
assertDefined(container, "#root element"); // instead of the `!` non-null assertion

createRoot(container).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

useEffect przerywa żądanie przez AbortController, gdy komponent znika (albo gdy StrictMode w trybie deweloperskim montuje go dwa razy). W poradniku React to samo pobieranie zastąpisz TanStack Query, które obsługuje cache, ponowienia i stany ładowania za Ciebie.

Krok 8. Ten sam kod w Node – bez kompilacji

Node 24 (i 22.18+) domyślnie wymazuje typy (type stripping): uruchamia plik .ts tak, jakby był JavaScriptem z usuniętymi adnotacjami. Nie ma kroku budowania ani ts-node. Warunek jest jeden: tylko składnia wymazywalna, czyli dokładnie to, czego pilnuje erasableSyntaxOnly. Skrypt używa tych samych schematów i funkcji domeny co aplikacja w przeglądarce:

scripts/check-orders.ts
// Run with plain Node 24: `node scripts/check-orders.ts` – types are stripped, nothing is compiled.
import { readFile } from "node:fs/promises";
import { z } from "zod";
import { OrderSchema } from "../src/api/schemas.ts";
import { describeStatus, totalCents } from "../src/domain/status.ts";

const file = new URL("../public/orders.json", import.meta.url);
const items = z.array(z.unknown()).parse(JSON.parse(await readFile(file, "utf8")));

let failed = 0;
for (const [index, item] of items.entries()) {
  const result = OrderSchema.safeParse(item);
  if (result.success) {
    const order = result.data;
    console.log(`OK   ${order.id} ${order.customer}: ${describeStatus(order.status)}, ${totalCents(order) / 100} PLN`);
  } else {
    failed++;
    console.error(`FAIL item #${index}\n${z.prettifyError(result.error)}`);
  }
}
process.exitCode = failed > 0 ? 1 : 0;
npm run check:orders
# OK   ord_1042 Halina K.: Zdzisław is on the way (12 min), 64 PLN
# OK   ord_1043 Marek W.: In the kitchen, ready in ~18 min, 58 PLN
# OK   ord_1044 Ola P.: Delivered at 1:41:00 PM, 59 PLN
# FAIL item #3
# ✖ Too small: expected string to have >=1 characters
#   → at customer
# ...

Podział ról jest prosty: Node i Vite uruchamiają kod, tsc tylko go sprawdza. W CI uruchamiasz npm run typecheck (tsc -b), a w edytorze działa serwer językowy TypeScript 7 – szybki nawet w dużych monorepo. Jeśli publikujesz bibliotekę, nadal kompilujesz ją do .js i .d.ts, ale aplikacje i skrypty tego nie potrzebują.

Typowe pułapki

Najgroźniejsze błędy w TypeScripcie to te, które się kompilują. Każdy fragment poniżej przechodzi tsc bez ostrzeżeń, a w runtime kończy się błędem albo cichym NaN:

examples/pitfalls.ts
// Everything below COMPILES – that is exactly the problem.

// 1. `as` is a promise to the compiler, not a conversion or a check.
type Customer = { id: number; email: string };
const customer = JSON.parse('{"id":"7"}') as Customer; // id is a string, email is missing
console.log(customer.email.toLowerCase()); // TypeError at runtime

// 2. `any` is contagious: whatever touches it loses its type.
function legacyTotal(): any {
  return { total: "12.50" };
}
const total: number = legacyTotal().total; // a string pretending to be a number
console.log(total.toFixed(2)); // TypeError at runtime

// 3. Optional chaining hides a missing value instead of handling it.
type Delivery = { courier?: { name: string; etaMinutes: number } };
const delivery: Delivery = {};
console.log(`Ready in ${delivery.courier?.etaMinutes} min`); // "Ready in undefined min"

// 4. The non-null assertion `!` just moves the crash elsewhere.
const prices = new Map<string, number>([["ruskie", 32]]);
console.log(prices.get("pierogi-z-mięsem")! * 2); // NaN, no error

// 5. Object.keys() returns string[] on purpose – objects may carry extra keys at runtime.
const menu = { ruskie: 32, meat: 36 };
for (const key of Object.keys(menu) as (keyof typeof menu)[]) {
  console.log(key, menu[key]); // OK only because WE know there are no extra keys
}

// Safer alternatives: `unknown` + schema (zod), narrowing, explicit undefined handling,
// Object.entries(), and string unions instead of enums.

Kilka mniej oczywistych zasad:

  • any zostaw w kodzie migracyjnym i oznacz komentarzem z zadaniem do zrobienia. W nowym kodzie używaj unknown – wymusza zawężenie.
  • Unia literałów zamiast enum. type Tag = "vegan" | "spicy" nie generuje kodu, działa z erasableSyntaxOnly i daje się iterować przez tablicę as const.
  • Object.keys() zwraca string[] celowo – obiekt może mieć w runtime więcej kluczy, niż mówi typ. Rzutuj tylko wtedy, gdy sam tworzysz obiekt.
  • // @ts-ignore zamieniaj na // @ts-expect-error – ten drugi zgłosi błąd, gdy problem zniknie, więc nie zostanie w kodzie na zawsze.

Ściąga: kiedy czego użyć

SytuacjaNarzędzie
Obiekt, który ktoś rozszerza (props, kontrakt)interface
Kilka wykluczających się stanówunia dyskryminowana + switch z assertNever
Dane z sieci, plików, formularzyunknown + schemat Zod, typ przez z.infer
Stała konfiguracja, mapa kolorów, opcjeas const satisfies …
Identyfikatory, których nie wolno mylićtypy z markerem (branded types)
Funkcja działająca dla wielu typówgeneryk z ograniczeniem (extends)
Wariant istniejącego modelu (formularz, PATCH)Pick, Omit, Partial zamiast kopii

Sprawdź się

Pytanie: Dodajesz do `OrderStatus` nowy wariant `{ kind: "refunded"; amountCents: number }`. Co się stanie z funkcją `describeStatus`?

  • Nic – zwróci `undefined` dla nowego statusu
  • Projekt przestanie się kompilować w linii `assertNever(status)`
  • TypeScript doda brakujący `case` automatycznie

Pytanie: Który zapis najlepiej typuje odpowiedź z `fetch`?

  • `const data = (await res.json()) as Order[]`
  • `const data: any = await res.json()`
  • `const data = OrderListSchema.parse(await res.json())`
Pytanie rekrutacyjne: czym różni się unknown od any i kiedy używać never?

any wyłącza sprawdzanie typów: wartość można przypisać wszędzie i wywołać na niej cokolwiek, a „zaraża” wszystko, czego dotknie. unknown to bezpieczny odpowiednik – można do niego przypisać wszystko, ale zanim go użyjesz, musisz zawęzić typ (typeof, instanceof, in, schemat). Dlatego unknown to właściwy typ dla danych z zewnątrz i dla catch (e). never to typ bez wartości: zwracają go funkcje, które zawsze rzucają wyjątek, i zostaje w gałęzi default wyczerpującego switch. Przypisanie czegokolwiek do never jest błędem, dlatego assertNever(x: never) zamienia nieobsłużony wariant unii w błąd kompilacji.

Co dalej