Polski

Tutorial · TypeScript · React

TypeScript for React and Node developers – from types to a type-safe API

A hands-on TypeScript 7 guide built around one project – a dumpling shop's order dashboard in React plus a Node script. Types vs interfaces, discriminated unions, narrowing, generics, utility types, a strict tsconfig and validating API responses with Zod.

By · · 26 min read

TypeScript isn't there to make the compiler stop complaining. Its job is to make invalid application states impossible to write down in the first place. In this guide you'll build a small but complete project: an order dashboard for a dumpling shop in React, plus a Node script that checks the data coming from the API. Along the way you'll cover everything you use day to day – from choosing between type and interface to validating JSON from the server.

Prerequisites: Node.js 24 (or 22.18+), JavaScript basics (ES2015+, async/await, modules) and React basics (components, props, useState). No prior TypeScript version knowledge required.

7.0
TypeScript version – native compiler written in Go
8–12×
faster full builds – according to the TypeScript team
strict
default since 6.0 – no need to switch it on by hand
0
`any` in app code – `unknown` + a schema instead of guessing

Step 0. A project and a tsconfig that actually guards you

Start from the Vite template – it generates two config files: one for browser code and one for files run by Node (the Vite config, scripts).

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

TypeScript 6.0 was a transition release that flipped several defaults, and 7.0 removed the old options for good. If you're moving an older project, these are the changes that surprise people most:

OptionNow (6.0/7.0)What it means in practice
stricttrue by defaultnull/undefined and implicit any are errors from day one
types[] by defaultglobal types (process, describe) must be listed, e.g. "types": ["node"]
module / targetesnext / latest ESno more ES5 output – the lowest target is ES2015
baseUrl, moduleResolution: "node"removed in 7.0use bundler (Vite) or nodenext (Node) and aliases via paths
esModuleInterop: falsenot alloweddefault imports from CommonJS packages simply work

Here's the project configuration. On top of the template settings we added noUncheckedIndexedAccess (indexing an array or record may return undefined) and noImplicitOverride:

Project configuration

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>

A few flags deserve a closer look:

  • verbatimModuleSyntax – imports used only as types must say import type. Tools that just erase types (Vite, Node) then don't have to guess what to drop.
  • erasableSyntaxOnly – forbids constructs that emit runtime code: enum, value namespaces and constructor parameter properties (constructor(private x: number)). Use literal unions instead of enum.
  • allowImportingTsExtensions – you import ./App.tsx, not ./App. Vite and Node both understand imports written that way.
  • noUncheckedIndexedAccess – orders[0] is Order | undefined. Annoying at first, but it catches real bugs with empty lists.

Step 1. Types or interfaces?

It's the most common question, and the good news is that for plain objects both work almost the same. The differences are in the details:

interfacetype
Object shapeyesyes
Unions, tuples, primitivesnoyes ("vegan" | "spicy", [number, number])
Mapped and conditional typesnoyes (Record<…>, Pick<…>, T extends U ? …)
Extendingextends, readable errors& (intersection), errors can be less readable
Declaration mergingyes – two declarations with the same name mergeno – a duplicate is an error

A rule that works well in teams: interface for object shapes that others extend (contracts, props, models), type for anything that's a union or is computed from other types. What matters most is that the team sticks to one convention.

The dumpling shop's domain model uses both. Note the branded types – OrderId and MenuItemId are plain strings at runtime, but the compiler won't let you pass one where the other is expected:

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;

The __brand marker exists only in the type system. The only place where a plain string becomes an OrderId is toOrderId / toMenuItemId. You call them in the layer that validates API data and nowhere else.

Step 2. Discriminated unions and an exhaustive switch

The classic modelling mistake is one object with optional fields: status: string; courier?: string; etaMinutes?: number; reason?: string. That type happily accepts an order that is "cancelled, with a courier on the way and no cancellation reason". A discriminated union describes each state separately, and the shared kind field tells the compiler which variant you're handling.

Diagram: An order as a state machine – each state carries only its own fields

Inside case "delivering" TypeScript knows status.courier exists. In the default branch the type left over is never. If someone adds a "refunded" status and forgets to handle it, the assertNever(status) call stops compiling:

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);
}

isActive is a type predicate: it returns a boolean, but the status is ActiveStatus signature tells the compiler how to narrow after the check. Extract<OrderStatus, { kind: … }> picks the matching union members, so you don't retype them.

Step 3. Narrowing

Narrowing is how the compiler follows your ifs. You have several tools:

  • typeof x === "string" – primitives,
  • x instanceof Error – classes,
  • "message" in x – property presence (also works on unknown after typeof x === "object" && x !== null),
  • comparing with a literal (status.kind === "cooking") – discriminated unions,
  • predicates x is T and assertion functions asserts x is T – your own narrowing rules,
  • the satisfies operator – checks a value against a type without widening it.

Type guards and 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) is the template for every catch block. In JavaScript you can throw anything, not just an Error, so catch (e) gives you unknown and you have to narrow it. assertDefined replaces the ! operator – instead of a silent "surely not null" assumption you get a clear exception right where the problem is. satisfies Record<OrderStatusKind, string> guarantees every status has a colour. A typo like "canceled" in the map is flagged, while the object's type stays precise.

Step 4. Generics without fear

A generic is a type parameter: a function or component works for many types without losing track of which one was used. When you call a generic function you almost never write the type in angle brackets – the compiler infers it from the arguments.

Result, groupBy and a generic component

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>
  );
}

Things to notice:

  • Constraints – K extends PropertyKey and K extends keyof T say what you require from the parameter. So pluck(orders, "customer") returns string[], and pluck(orders, "costomer") is an error.
  • Result<T, E> turns exceptions into values. getOrders (step 6) returns Result<…, FetchError>, so the calling code has to handle the error – it can't be forgotten.
  • The generic Select<T> component takes options and a value of the same type. Instead of casting e.target.value as T it looks the selected option up in the list, so the type is real, not just declared.
  • Don't generify up front. If a type parameter appears only once in a signature, you can almost always drop it and use a plain type.

Step 5. Utility types

Utility types are functions on types: they turn one type into another. Thanks to them one model (Order) serves the form, the PATCH body, the list and the stats, instead of four hand-maintained copies.

TypeWhat it doesExample in the project
Pick<T, K> / Omit<T, K>keeps / removes fieldsOrderDraft = Omit<Order, "id" | "status">
Partial<T> / Required<T>all fields optional / requiredOrderPatch for PATCH
Readonly<T>read-only fieldsOrderSummary in lists
Record<K, V>object keyed by KStatusCounts, statusColors
Extract<T, U> / Exclude<T, U>filters a unionActiveStatus
ReturnType<F> / Awaited<T>a function's / promise's result typeOrdersResult
mapped type + as + template literalstransforms keysStatusHandlers → 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>>;

The last line matters: Awaited<ReturnType<typeof getOrders>> follows the code. Change what getOrders returns and the type changes with it – every place that no longer fits gets a compile error.

Step 6. Typing API responses with Zod

This is the most important step of the guide. TypeScript types vanish at runtime. const orders = await res.json() as Order[] checks nothing – it merely promises the compiler that the server definitely sent what you expect. When the backend changes the format or returns an HTML error page, the app crashes three components later with a message that tells you nothing.

Diagram: The trust boundary: everything from outside is unknown until it passes a schema

The Zod schema describes the wire format – snake_case, prices in grosze, dates as ISO strings – and .transform() maps it to the domain model. You derive OrderDto from the schema with z.infer, so schema and type can't drift apart. The (dto): Order annotation on transform makes the compiler check the mapping result against the domain model.

Data, schemas and the API client

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 });
}

Three design decisions worth copying into your own projects:

  1. fetchJson is generic over the schema (S extends z.ZodType) and returns z.output<S>. The result type comes from the schema you pass – you don't state it twice.
  2. Record-by-record validation. One broken record (ord_1045 in the sample data) doesn't blank the whole screen. It's skipped, and the number of rejected records reaches the UI. In an admin panel that's usually better than "something went wrong".
  3. Errors as a union FetchError (network / http / invalid-data). The component knows what to show in each case, and an exhaustive switch makes sure none is missed.

Types only (`as`)

  • zero extra code and no extra kilobytes in the bundle
  • enough for data you create yourself in the same process
  • bad data stopped at the boundary, with a readable message (`z.prettifyError`)
  • type derived from the schema – a single source of truth

Runtime validation (Zod)

  • doesn't notice format changes on the server side
  • the error surfaces far from its cause, often only for the user
  • an extra dependency (a dozen-odd kB) and parsing cost for large responses

Step 7. TypeScript in React components

Typing is simpler in React 19 than it used to be: ref is a regular prop (no forwardRef), and React.FC isn't needed – just type the function's parameter. The key patterns:

  • Props as an intersection: { order: Order } & Omit<ComponentProps<"article">, "children">. The component accepts every native attribute of the element (className, aria-*, data-*) and passes them on via ...rest.
  • State as a union: useState<LoadState> with loading / error / ready variants. There's no "loading and failed at the same time", and after if (state.status === "error") you can read state.error.
  • Event types: inline handlers (onChange={(e) => …}) are inferred. When the handler is defined separately, annotate it: ChangeEvent<HTMLInputElement>.
  • as const satisfies for constant options: literals stay exact ("cooking", not string) and the shape is checked.

Components and the app

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 aborts the request with an AbortController when the component unmounts (or when StrictMode mounts it twice in development). In the React guide you'll replace this fetching with TanStack Query, which handles caching, retries and loading states for you.

Step 8. The same code in Node – no build step

Node 24 (and 22.18+) does type stripping by default: it runs a .ts file as if it were JavaScript with the annotations removed. No build step, no ts-node. There's one condition: erasable syntax only, which is exactly what erasableSyntaxOnly enforces. The script uses the same schemas and domain functions as the browser app:

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
# ...

The split of roles is simple: Node and Vite run the code, tsc only checks it. In CI you run npm run typecheck (tsc -b), and in the editor the TypeScript 7 language server stays fast even in large monorepos. If you publish a library you still compile it to .js and .d.ts, but apps and scripts don't need that.

Common pitfalls

The most dangerous TypeScript bugs are the ones that compile. Every snippet below passes tsc without a warning and ends in a runtime error or a silent 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.

A few less obvious rules:

  • Keep any for migration code, marked with a TODO comment. In new code use unknown – it forces narrowing.
  • Literal unions instead of enum. type Tag = "vegan" | "spicy" emits no code, works with erasableSyntaxOnly and can be iterated via an as const array.
  • Object.keys() returns string[] on purpose – an object can have more keys at runtime than its type says. Cast only when you created the object yourself.
  • Replace // @ts-ignore with // @ts-expect-error – the latter reports an error once the problem disappears, so it doesn't linger forever.

Cheat sheet: what to use when

SituationTool
An object others extend (props, contract)interface
Several mutually exclusive statesdiscriminated union + switch with assertNever
Data from the network, files, formsunknown + Zod schema, type via z.infer
Constant config, colour maps, optionsas const satisfies …
Ids that must not be mixed upbranded types
A function that works for many typesa generic with a constraint (extends)
A variant of an existing model (form, PATCH)Pick, Omit, Partial instead of a copy

Check yourself

Question: You add a new variant `{ kind: "refunded"; amountCents: number }` to `OrderStatus`. What happens to `describeStatus`?

  • Nothing – it returns `undefined` for the new status
  • The project stops compiling at the `assertNever(status)` line
  • TypeScript adds the missing `case` automatically

Question: Which line types a `fetch` response best?

  • `const data = (await res.json()) as Order[]`
  • `const data: any = await res.json()`
  • `const data = OrderListSchema.parse(await res.json())`
Interview question: how is unknown different from any, and when do you use never?

any turns type checking off: the value can be assigned anywhere and you can call anything on it, and it "infects" everything it touches. unknown is the safe counterpart – anything can be assigned to it, but before using it you must narrow the type (typeof, instanceof, in, a schema). That's why unknown is the right type for external data and for catch (e). never is the type with no values: functions that always throw return it, and it's what remains in the default branch of an exhaustive switch. Assigning anything to never is an error, which is why assertNever(x: never) turns an unhandled union variant into a compile error.

What next