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.
Author: bezzad
Contents
The problem: bugs only the user sees
Our online shop is written in plain JavaScript. This week we had three bugs:
- The cart total showed “1205” instead of 125. The server sent the price as text, and the plus sign glued two texts together.
- The checkout page crashed with “Cannot read properties of undefined” for users who had no address.
- 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?
- 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”.
- The editor helps you. Auto-complete for fields, jump to definition, and safe renaming across all files.
- 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:
- The browser does not run TypeScript. The build tool (the tsc compiler or a bundler) first removes all types and produces plain JavaScript.
- 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.
- Any data that comes from outside (an API response, localStorage content, form input, URL parameters) must be checked at runtime.
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);
}
- Most of the time you do not need to write the type. TypeScript works it out from the value (inference).
- Always type function parameters. There is nothing to infer from there.
- 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';
- Both can describe the shape of an object. For daily work they differ very little.
- The type keyword can name any type: a union, a tuple, a function. The interface keyword is only for object shapes.
- An interface can be extended with extends. Two interfaces with the same name are also merged (declaration merging).
- 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}`;
}
- The typeof operator is for simple types like string and number.
- The in operator checks if a field exists in an object.
- 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;
}
}
}
- The orderId field exists only in the paid state. You cannot read it by mistake in the failed state.
- 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.
- 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.
The any type versus unknown
- 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.
- 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"
- The as keyword (a type assertion) only tells the compiler “trust me”. It creates no code at runtime.
- 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.
- 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 };
- The letter T is a type that is decided when you call the function. For products it is Product.
- The extends part is a rule: every T must have a numeric id field. So inside the function you can read item.id.
- 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
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
- The satisfies operator checks that the value matches the type. If a category is missing or misspelled, you get an error.
- 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
}
}
- 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.
- 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.
- 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
- TypeScript finds bugs before the code runs and makes the editor smarter.
- Types are erased at build time. Check data that comes from outside at runtime.
- Narrow a union with typeof, in, or a kind field. Use never to make sure no state is forgotten.
- Use unknown for unknown data, not any. A schema library like Zod gives you the check and the type together.
- The as keyword checks nothing.
- Generics make reusable code that keeps the exact type. Utility types build types from one source.
- The satisfies operator checks without changing the type. Always turn on strict.