My account

TypeScript

TypeScript adds types to JavaScript, so many bugs show up before the code runs, in the editor and at build time. But types are erased at runtime, so you must check data that comes from an API yourself. This lesson shows unions and narrowing, any versus unknown, generics, utility types, satisfies and strict settings, using the online shop example.

Not reviewedWritten with AI helpReading time: 16 minOnline shop exampleTypeScript 5 code

Author: bezzad

Contents

The problem: bugs only the user sees

Our online shop is written in plain JavaScript. This week we had three bugs:

  1. The cart total showed “1205” instead of 125. The server sent the price as text, and the plus sign glued two texts together.
  2. The checkout page crashed with “Cannot read properties of undefined” for users who had no address.
  3. A developer renamed the price field to unitPrice. Three other files still read price, and nobody noticed.

None of these bugs showed up in the editor. The user found all of them.

Why TypeScript?

  1. Bugs are found before the code runs. The TypeScript compiler reads the code and says “this may be undefined” or “the price field no longer exists”.
  2. The editor helps you. Auto-complete for fields, jump to definition, and safe renaming across all files.
  3. Types are living documentation. From a function’s signature you see what it takes and what it returns.

Types do not exist at runtime

This is the most important point about TypeScript:

  1. The browser does not run TypeScript. The build tool (the tsc compiler or a bundler) first removes all types and produces plain JavaScript.
  2. So there is no type check at runtime. If the API sends text instead of a number, you get no error. The result is just wrong.
  3. Any data that comes from outside (an API response, localStorage content, form input, URL parameters) must be checked at runtime.
Build time: types are checked, then removedtotal.tsfunction total(p: Product) {return p.price + 5;}total.jsfunction total(p) {return p.price + 5;}tscRuntime: there are no typesGET /api/products/7{ "price": "120" }"120" + 5 = "1205"Nobody checks the data type at runtime, except you.
The compiler only checks your code. After the build, the types are gone, and data from the server enters the code with no check at all.

Basic types

let title: string = 'Phone';
let price = 120;                     // inferred as number
const tags: string[] = ['new', 'sale'];
const line: [string, number] = ['pen', 2]; // a tuple: name and quantity

function addToCart(productId: number, quantity = 1): void {
  console.log(productId, quantity);
}
  1. Most of the time you do not need to write the type. TypeScript works it out from the value (inference).
  2. Always type function parameters. There is nothing to infer from there.
  3. The void type means the function returns nothing useful.

The type and interface keywords

interface Product {
  readonly id: number; // cannot be changed after creation
  title: string;
  price: number;
  badge?: string;      // optional: string or missing
}

type ProductId = number;
type LoadStatus = 'idle' | 'loading' | 'error';
  1. Both can describe the shape of an object. For daily work they differ very little.
  2. The type keyword can name any type: a union, a tuple, a function. The interface keyword is only for object shapes.
  3. An interface can be extended with extends. Two interfaces with the same name are also merged (declaration merging).
  4. Practical rule: pick one and be consistent in the whole project. Many teams use interface for objects and type for everything else.

Union types and narrowing

A union type means “one of these”. Before you use it, you must find out which one it is. This is called narrowing:

function formatPrice(price: number | string): string {
  if (typeof price === 'string') return price; // here price is a string
  return price.toFixed(2);                     // here price is a number
}

type Card = { cardNumber: string };
type Wallet = { walletId: string };

function describePayment(method: Card | Wallet): string {
  if ('cardNumber' in method) return `Card ending ${method.cardNumber.slice(-4)}`;
  return `Wallet ${method.walletId}`;
}
  1. The typeof operator is for simple types like string and number.
  2. The in operator checks if a field exists in an object.
  3. After the check, TypeScript knows the exact type in each branch.

Discriminated unions

People often write the payment state with several booleans: isLoading, isError, and some data. Then impossible states become possible, like “loading and error at the same time”. It is better to give each state a kind field:

type PaymentState =
  | { kind: 'idle' }
  | { kind: 'paying' }
  | { kind: 'paid'; orderId: string }
  | { kind: 'failed'; error: string };

function paymentMessage(state: PaymentState): string {
  switch (state.kind) {
    case 'idle':
      return 'Ready to pay';
    case 'paying':
      return 'Paying...';
    case 'paid':
      return `Order ${state.orderId} is placed`;
    case 'failed':
      return `Payment failed: ${state.error}`;
    default: {
      const unreachable: never = state; // error here if a kind is not handled
      return unreachable;
    }
  }
}
  1. The orderId field exists only in the paid state. You cannot read it by mistake in the failed state.
  2. The never type means “no value at all”. If you handled every state, nothing is left for state in the default branch, and its type is never.
  3. Tomorrow someone adds a refunded state. Now state in the default branch has the refunded type, and it cannot be put in a never variable. The compiler gives an error and points to exactly the place that was forgotten.
switch (state.kind)'idle''paying''paid'orderId: string'failed'error: stringIn each branch, only that state's fields are available.default: const x: never = stateIf a new state is added and forgotten here, the build fails.
The kind field says which state it is. In each branch, only that state's fields are available. The never branch finds forgotten states.

The any type versus unknown

  1. The any type turns checking off. Anything is allowed with it, and the error moves to runtime. It spreads like a virus: anything you read from it is any too.
  2. The unknown type means “I do not know what this is”. Until you check it, you are not allowed to do anything with it.
const data: unknown = await res.json();

data.title; // compile error: 'data' is of type 'unknown'

if (typeof data === 'object' && data !== null && 'title' in data && typeof data.title === 'string') {
  console.log(data.title.toUpperCase()); // OK: checked
}

Choose unknown for data that comes from an API. Checking a full object by hand gets long. A common option is a schema library like Zod. The same schema checks the data at runtime and also creates the TypeScript type:

import { z } from 'zod';

const ProductSchema = z.object({
  id: z.number(),
  title: z.string(),
  price: z.number(),
  badge: z.string().optional(),
});
type Product = z.infer<typeof ProductSchema>;

async function loadProduct(id: number): Promise<Product> {
  const res = await fetch(`/api/products/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return ProductSchema.parse(await res.json()); // throws if the data has the wrong shape
}

With this code, the server’s text price is found right away with a clear error, not in the cart total.

The as keyword checks nothing

const product = (await res.json()) as Product; // no check at all
product.price.toFixed(2); // crashes at runtime if price is the text "120"
  1. The as keyword (a type assertion) only tells the compiler “trust me”. It creates no code at runtime.
  2. The compiler rejects only completely unrelated conversions, for example text to number. Writing as unknown as to get around this is a red flag in code review.
  3. Use as only when you really know more than the compiler. For example, when the element you find with querySelector is surely an input.

Generics

A generic is like a parameter for a type. You write one function that works with many types and still keeps the exact type:

function findById<T extends { id: number }>(items: readonly T[], id: number): T | undefined {
  return items.find((item) => item.id === id);
}

const product = findById(products, 7); // Product | undefined
const order = findById(orders, 42);    // Order | undefined

type ApiResult<T> =
  | { ok: true; data: T }
  | { ok: false; error: string };
  1. The letter T is a type that is decided when you call the function. For products it is Product.
  2. The extends part is a rule: every T must have a numeric id field. So inside the function you can read item.id.
  3. It would also work with any, but the result would be any, and the editor would no longer know the fields of Product.

Utility types

Build other types from one main type, so they all stay in sync:

type ProductPatch = Partial<Product>;                      // every field optional: an edit form
type ProductCard = Pick<Product, 'id' | 'title' | 'price'>; // only what a card shows
type NewProduct = Omit<Product, 'id'>;                     // the server creates the id
type StockByProductId = Record<number, number>;            // product id to stock count
type FrozenProduct = Readonly<Product>;                    // no field can be changed
Productid: numbertitle: stringprice: numberbadge?: stringPartial<Product>id?, title?, price?, badge?Edit formPick<Product, 'id' | 'title' | 'price'>id, title, priceProduct cardOmit<Product, 'id'>title, price, badge?New productReadonly<Product>readonly id, readonly title, ...Read-only
All these types are built from Product. If a field in Product changes, the others change with it.

This fixes the third bug. If price in Product is renamed to unitPrice, all code that reads price, and the Pick type that names price, get a compile error. The Readonly type makes only one level read-only, not the inner objects.

The satisfies operator

type Category = 'phones' | 'laptops' | 'books';

const categoryLabels = {
  phones: 'Phones',
  laptops: 'Laptops',
  books: 'Books',
} satisfies Record<Category, string>;

const config = {
  apiUrl: 'https://shop.example.com',
  retries: 3,
} satisfies Record<string, string | number>;

config.retries.toFixed(0); // OK: retries is still a number
  1. The satisfies operator checks that the value matches the type. If a category is missing or misspelled, you get an error.
  2. But it does not change the value’s own type. If you wrote the type with a colon instead, retries would be string or number, and the toFixed method would give an error.

Strict settings

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}
  1. The strict option turns on several important checks together. The most important ones are:
    • The strictNullChecks option: null and undefined are separate types. The shop’s second bug (an undefined address) would be found here.
    • The noImplicitAny option: if TypeScript cannot work out a type, it gives an error instead of quietly using any.
    • The useUnknownInCatchVariables option: the catch variable is unknown, not any.
  2. The noUncheckedIndexedAccess option is not part of strict, but it is useful. With it, reading an array item has the type T or undefined, because that item may not exist.
  3. Start a new project with strict from day one. Turning it on in a big old project gives hundreds of errors.

Common mistakes

Mistake Result Better way
Thinking types are checked at runtime Wrong API data enters the app quietly. Check outside data, for example with Zod.
The any type for an API response No checks, and any spreads. The unknown type, then a check.
The as keyword on an API response Only the compiler goes quiet. A schema or a type guard.
Several booleans for a state Impossible states. A union with a kind field.
A default branch without never A new state is quietly forgotten. A never variable in default.
Writing similar shapes again When one changes, the others get old. The Pick, Omit and Partial types on the main type.
Strict turned off Null and undefined bugs are not seen. Turn on the strict option.

Summary in seven lines

  1. TypeScript finds bugs before the code runs and makes the editor smarter.
  2. Types are erased at build time. Check data that comes from outside at runtime.
  3. Narrow a union with typeof, in, or a kind field. Use never to make sure no state is forgotten.
  4. Use unknown for unknown data, not any. A schema library like Zod gives you the check and the type together.
  5. The as keyword checks nothing.
  6. Generics make reusable code that keeps the exact type. Utility types build types from one source.
  7. The satisfies operator checks without changing the type. Always turn on strict.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.