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.
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ą:
| Opcja | Teraz (6.0/7.0) | Co to znaczy w praktyce |
|---|---|---|
strict | true domyślnie | null/undefined i niejawne any są błędami od pierwszego dnia |
types | [] domyślnie | globalne typy (process, describe) trzeba wskazać jawnie, np. "types": ["node"] |
module / target | esnext / najnowszy ES | koniec z kompilacją do ES5 – najniższy cel to ES2015 |
baseUrl, moduleResolution: "node" | usunięte w 7.0 | używaj bundler (Vite) albo nodenext (Node) i aliasów przez paths |
esModuleInterop: false | niedozwolone | domyś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
{
"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"
}
}{
"files": [],
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.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"]
}{
"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"]
}import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react()],
});<!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,namespacez wartościami i właściwości w parametrach konstruktora (constructor(private x: number)). Zamiastenumużywasz unii literałów.allowImportingTsExtensions– importujesz./App.tsx, a nie./App. Tak samo zapisany import zrozumie Vite i Node.noUncheckedIndexedAccess–orders[0]ma typOrder | 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:
interface | type | |
|---|---|---|
| Kształt obiektu | tak | tak |
| Unie, krotki, typy prymitywne | nie | tak ("vegan" | "spicy", [number, number]) |
| Typy mapowane i warunkowe | nie | tak (Record<…>, Pick<…>, T extends U ? …) |
| Rozszerzanie | extends, 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:
// 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.
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ć:
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ż naunknownpo sprawdzeniutypeof x === "object" && x !== null),- porównanie z literałem (
status.kind === "cooking") – unie dyskryminowane, - predykaty
x is Ti funkcje asercjiasserts 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
// 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);
}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
// 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]);
}// 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 PropertyKeyiK extends keyof Tmówią, czego wymagasz od parametru. Dzięki temupluck(orders, "customer")zwracastring[], apluck(orders, "costomer")jest błędem. Result<T, E>zamienia wyjątki w wartości. FunkcjagetOrders(krok 6) zwracaResult<…, 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 rzutowaniae.target.value as Tszuka 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.
| Typ | Co robi | Przykład w projekcie |
|---|---|---|
Pick<T, K> / Omit<T, K> | wybiera / usuwa pola | OrderDraft = Omit<Order, "id" | "status"> |
Partial<T> / Required<T> | wszystkie pola opcjonalne / wymagane | OrderPatch dla PATCH |
Readonly<T> | pola tylko do odczytu | OrderSummary w liście |
Record<K, V> | obiekt o kluczach K | StatusCounts, statusColors |
Extract<T, U> / Exclude<T, U> | filtruje unię | ActiveStatus |
ReturnType<F> / Awaited<T> | typ wyniku funkcji / obietnicy | OrdersResult |
typ mapowany + as + szablony | przekształca klucze | StatusHandlers → onPlaced, onCooking… |
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.
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
[
{
"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" }
}
]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,
}),
);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:
fetchJsonjest generyczny względem schematu (S extends z.ZodType) i zwracaz.output<S>. Typ wyniku wynika ze schematu, który przekazujesz – nie podajesz go drugi raz.- Walidacja rekord po rekordzie. Jeden zepsuty rekord (
ord_1045w 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”. - Błędy jako unia
FetchError(network/http/invalid-data). Komponent wie, co pokazać w każdym przypadku, a wyczerpującyswitchpilnuje, ż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 wariantamiloading/error/ready. Nie ma kombinacji „ładuje się i jednocześnie ma błąd”, a poif (state.status === "error")masz dostęp dostate.error. - Typy zdarzeń: inline (
onChange={(e) => …}) są wnioskowane same. Gdy handler jest zdefiniowany osobno, podaj typ:ChangeEvent<HTMLInputElement>. as const satisfiesdla stałych opcji: literały zostają dokładne ("cooking", a niestring), a kształt jest sprawdzony.
Komponenty i aplikacja
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>
);
}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>
);
}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:
// 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:
// 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:
anyzostaw w kodzie migracyjnym i oznacz komentarzem z zadaniem do zrobienia. W nowym kodzie używajunknown– wymusza zawężenie.- Unia literałów zamiast
enum.type Tag = "vegan" | "spicy"nie generuje kodu, działa zerasableSyntaxOnlyi daje się iterować przez tablicęas const. Object.keys()zwracastring[]celowo – obiekt może mieć w runtime więcej kluczy, niż mówi typ. Rzutuj tylko wtedy, gdy sam tworzysz obiekt.// @ts-ignorezamieniaj 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ć
| Sytuacja | Narzędzie |
|---|---|
| Obiekt, który ktoś rozszerza (props, kontrakt) | interface |
| Kilka wykluczających się stanów | unia dyskryminowana + switch z assertNever |
| Dane z sieci, plików, formularzy | unknown + schemat Zod, typ przez z.infer |
| Stała konfiguracja, mapa kolorów, opcje | as const satisfies … |
| Identyfikatory, których nie wolno mylić | typy z markerem (branded types) |
| Funkcja działająca dla wielu typów | generyk 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
React – Komponenty, hooki, TanStack Query i formularze z react-hook-form + Zod
Stan (State) – Kiedy unia dyskryminowana wystarczy, a kiedy potrzebny jest wzorzec Stan
Adapter – Mapowanie DTO → model domeny to adapter na granicy systemu
MUI – Typowany motyw i własne warianty komponentów Material UI