Skip to content
LumenaryAcademy
Professional 75 min

TypeScript in practice

The strictness options, bringing TypeScript into JavaScript projects and frameworks, validating data at the boundary, and a complete project.

Code tested · 2AI-draftedAwaiting review by a computer scientist
MotivationH

From a language to a practice

You now know the language: types for values, objects, unions, functions, generics and classes, and types computed from types. Using TypeScript well on a real team involves a few more decisions. How strict should the compiler be? How do you bring types into a JavaScript code base of fifty thousand lines without stopping work for a month? How does TypeScript fit with React, Vue, Angular or a Node server? And what happens at the edges of the program, where data arrives that no type annotation can vouch for?

This lesson answers those questions, then puts the whole course together in a complete program that validates untrusted input, derives its types from a single schema, and computes a priced report with discriminated unions, generics and mapped types.

DefinitionsH

How strict?

Definition— strict mode

The strict option turns on a family of checks that together make TypeScript's types trustworthy: noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, useUnknownInCatchVariables, alwaysStrict, and any check that later versions add to the family. Since TypeScript 6.0 it is on by default; in earlier versions you must set it.

Without strict, TypeScript is a much weaker tool. With strict off (the default before TypeScript 6.0), this file compiles without a single complaint:

typescript
function total(items) {
  return items.reduce((sum, x) => sum + x.price, 0);
}
let label: string = null;
try { JSON.parse("{"); } catch (err) { console.log(err.message); }

With --strict:

text
main.ts(1,16): error TS7006: Parameter 'items' implicitly has an 'any' type.
main.ts(2,24): error TS7006: Parameter 'sum' implicitly has an 'any' type.
main.ts(2,29): error TS7006: Parameter 'x' implicitly has an 'any' type.
main.ts(4,5): error TS2322: Type 'null' is not assignable to type 'string'.
main.ts(5,52): error TS18046: 'err' is of type 'unknown'.

Every new project should use strict. Beyond it, several options catch more, at the cost of more checks in your code. The ones most worth knowing:

OptionWhat it adds
noUncheckedIndexedAccessreading array[i] or record[key] gives T | undefined
exactOptionalPropertyTypesx?: T means "absent or T", not "absent, T or undefined"
noImplicitOverridemethods that replace a parent's must say override
noImplicitReturnsevery path through a function must return a value
noFallthroughCasesInSwitchnon-empty case blocks may not fall through
noPropertyAccessFromIndexSignaturedictionary keys must be read with brackets, so obj.typo stands out

The first two are the most valuable, and tsc --init turns them on (lesson one). This code compiles under --strict alone:

typescript
const scores: Record<string, number> = { Aiko: 91, Bilal: 78 };
const first = [3, 1, 4][0];
console.log(scores["Chidi"].toFixed(0), first.toFixed(0));

interface Profile {
  nickname?: string;
}
const p: Profile = { nickname: undefined };

but adding --noUncheckedIndexedAccess --exactOptionalPropertyTypes gives:

text
main.ts(3,13): error TS2532: Object is possibly 'undefined'.
main.ts(3,41): error TS18048: 'first' is possibly 'undefined'.
main.ts(8,7): error TS2375: Type '{ nickname: undefined; }' is not assignable to type 'Profile' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  Types of property 'nickname' are incompatible.
    Type 'undefined' is not assignable to type 'string'.

The first error is a real bug: there is no "Chidi" in scores, and the program would crash. The second is a false alarm ([3, 1, 4][0] obviously exists), and that is the price of the option: some accesses need a check or a ! that you know is safe. Most teams that try it keep it, because the real bugs it finds are exactly the ones that reach production. Code written for these options handles every lookup and every optional property explicitly:

typescript
// Code written to pass the strictest options: every lookup and every optional handled.
const scores: Record<string, number> = { Aiko: 91, Bilal: 78 };

function scoreOf(name: string): string {
  const score = scores[name];                  // number | undefined with noUncheckedIndexedAccess
  return score === undefined ? `${name}: no score yet` : `${name}: ${score}`;
}

function median(values: readonly number[]): number | undefined {
  const sorted = [...values].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  const upper = sorted[mid];
  const lower = sorted[mid - 1];
  if (upper === undefined) return undefined;   // empty input
  return sorted.length % 2 === 1 || lower === undefined ? upper : (lower + upper) / 2;
}

interface Profile {
  name: string;
  nickname?: string;                           // absent or a string, never undefined
}

// Add an optional property only when there is a value for it.
function makeProfile(name: string, nickname?: string): Profile {
  return { name, ...(nickname !== undefined && { nickname }) };
}

console.log(scoreOf("Aiko"), "|", scoreOf("Chidi"));
console.log(median([7, 3, 9, 1]), median([5]), median([]));
console.log(makeProfile("Valentina", "Vale"), makeProfile("Tomás"));
console.log("nickname" in makeProfile("Tomás"));

export {};
text
Aiko: 91 | Chidi: no score yet
5 5 undefined
{ name: 'Valentina', nickname: 'Vale' } { name: 'Tomás' }
false

This program compiles under --strict and also with --noUncheckedIndexedAccess --exactOptionalPropertyTypes --noImplicitReturns --noFallthroughCasesInSwitch. scoreOf and median compare each lookup with undefined before using it, which narrows the type and handles the missing case at the same time. makeProfile uses a spread of a conditional object to add nickname only when there is one: with exactOptionalPropertyTypes, writing { name, nickname } with an undefined nickname would be an error, and at run time the property would exist with the value undefined, which "nickname" in profile would report as present. The project below compiles cleanly with all of these options too.

ExplanationH

Bringing TypeScript into a JavaScript project

Few teams get to start from scratch. The usual path is gradual, and TypeScript was designed for it.

  1. Add a tsconfig.json with allowJs, so the compiler accepts .js files alongside .ts, and noEmit if another tool already builds the project. Nothing changes yet, but the editor starts offering better completion.
  2. Type-check JavaScript files with checkJs, or one file at a time with a // @ts-check comment at the top. TypeScript infers what it can, and reads types from JSDoc comments:
javascript
// @ts-check

/**
 * @typedef {{ sku: string, priceCents: number, qty: number }} Line
 */

/**
 * @param {Line[]} lines
 * @returns {number}
 */
export function totalCents(lines) {
  return lines.reduce((sum, line) => sum + line.priceCents * line.qty, 0);
}

totalCents([{ sku: "tea", priceCents: "450", qty: 2 }]);
text
cart.js(15,27): error TS2322: Type 'string' is not assignable to type 'number'.

This is real type checking in a file that stays plain JavaScript: no build step, the same syntax as the JavaScript course. Some well-known libraries are written this way on purpose. 3. Rename files from .js to .ts one at a time, starting with the leaves (utilities with no internal imports) and working inwards, adding annotations as you go. Install @types packages for dependencies. 4. Tighten the options as the code allows: strict first, which you can turn on early and fix gradually, then the extra checks. Where an error cannot be fixed yet, // @ts-expect-error with a reason on the line above silences exactly one error, and itself becomes an error when the problem is fixed, so suppressions don't outlive their purpose. Prefer it to // @ts-ignore, which stays silent forever.

Large companies have migrated code bases of millions of lines this way, over months, without a pause in feature work. The engineering blogs of several of them describe it in detail; the handbook's migration guide, linked above, is the official starting point.

Worked examplesH

TypeScript with frameworks and servers

Every major framework supports TypeScript, and most are written in it. In React, components are functions whose props are described by an interface, and files that contain JSX use the .tsx extension:

tsx
import { useState, type MouseEvent } from "react";

interface CounterProps {
  label: string;
  start?: number;
  onChange?: (value: number) => void;
}

export function Counter({ label, start = 0, onChange }: CounterProps) {
  const [count, setCount] = useState(start);                // number, inferred from start
  const [note, setNote] = useState<string | null>(null);    // explicit: null now, a string later

  function handleClick(event: MouseEvent<HTMLButtonElement>) {
    const next = event.shiftKey ? count + 10 : count + 1;
    setCount(next);
    setNote(next >= 100 ? "that's a lot" : null);
    onChange?.(next);
  }

  return (
    <button type="button" onClick={handleClick}>
      {label}: {count} {note}
    </button>
  );
}

export const usage = <Counter label="Cups of tea" start={2} onChange={(n) => console.log(n)} />;

Type-checked against React's own types (with --jsx react-jsx), this component catches mistakes at every place it is used. Two bad uses:

tsx
export const bad1 = <Counter label={3} />;
export const bad2 = <Counter label="Tea" strat={2} />;
text
Bad.tsx(2,30): error TS2322: Type 'number' is not assignable to type 'string'.
Bad.tsx(3,42): error TS2322: Type '{ label: string; strat: number; }' is not assignable to type 'IntrinsicAttributes & CounterProps'.
  Property 'strat' does not exist on type 'IntrinsicAttributes & CounterProps'. Did you mean 'start'?

Note how much is inferred: count is a number from start, and the onChange arrow's parameter n is a number from the props interface. The explicit useState<string | null>(null) is the case the generics lesson described, where the initial value alone can't tell the compiler what will come later.

  • Vue single-file components use <script setup lang="ts">, and the vue-tsc tool type-checks templates as well as scripts.
  • Angular is written in TypeScript and uses it by default, with classes, decorators and dependency injection throughout.
  • Svelte and Solid support TypeScript in components, with their own checkers for templates.
  • Node servers: frameworks such as Express (with @types/express), Fastify and Hono provide types for requests and responses; several can derive request types from route definitions and schemas, using the techniques of the last lesson.

Whatever the framework, add typescript-eslint, which runs ESLint rules that use type information. Its no-floating-promises rule catches a forgotten await, no-misused-promises catches an async function passed where a plain callback is expected, and no-explicit-any and no-unsafe-* rules keep any from spreading. Together with tsc --noEmit in continuous integration, they form the safety net of a professional TypeScript project.

IntuitionH

Types at the boundary

Lesson one showed that types cannot check data that arrives at run time: a JSON.parse result asserted to be a User may be anything. The professional solution is a schema: an ordinary value that describes the expected shape, can validate data at run time, and from which the static type is derived, so the run-time check and the compile-time type can never disagree. Libraries such as Zod, Valibot and ArkType provide rich versions; the project below builds a small one from scratch, so you can see that there is no magic involved, only the generics, conditional types and mapped types of the last two lessons.

The principle is the one lesson four called "parse, don't validate": at the edge of the program, turn unknown into a precise type or a clear error, once; inside, trust the types completely.

ComputationC

Project: validated orders, priced and reported

A shop receives order submissions as JSON. Some are malformed. The program must reject bad orders with messages that say exactly what is wrong, price the good ones using a discount that depends on the customer's tier, and print a report. Every type comes from one of two sources of truth: the schema, and the discount table.

typescript
// orders.ts: validate raw order submissions, price them, and report, with types end to end.

// ---------- 1. A tiny schema library: each schema can parse unknown data into a typed value ----------
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

interface Schema<T> {
  parse(input: unknown, path?: string): Result<T>;
}
type Infer<S> = S extends Schema<infer T> ? T : never;

const ok = <T>(value: T): Result<T> => ({ ok: true, value });
const fail = (path: string, expected: string, got: unknown): Result<never> => ({
  ok: false,
  error: `${path || "value"}: expected ${expected}, got ${JSON.stringify(got)}`,
});

const string = (): Schema<string> => ({
  parse: (x, path = "") => (typeof x === "string" && x.trim() !== "" ? ok(x.trim()) : fail(path, "a non-empty string", x)),
});

const integer = (min: number, max: number): Schema<number> => ({
  parse: (x, path = "") =>
    Number.isInteger(x) && (x as number) >= min && (x as number) <= max
      ? ok(x as number)
      : fail(path, `an integer from ${min} to ${max}`, x),
});

const oneOf = <const T extends readonly string[]>(...options: T): Schema<T[number]> => ({
  parse: (x, path = "") =>
    typeof x === "string" && (options as readonly string[]).includes(x)
      ? ok(x as T[number])
      : fail(path, options.join(" | "), x),
});

const array = <T>(item: Schema<T>, minLength = 0): Schema<T[]> => ({
  parse: (x, path = "") => {
    if (!Array.isArray(x) || x.length < minLength) return fail(path, `an array of at least ${minLength}`, x);
    const out: T[] = [];
    for (const [i, el] of x.entries()) {
      const r = item.parse(el, `${path}[${i}]`);
      if (!r.ok) return r;
      out.push(r.value);
    }
    return ok(out);
  },
});

const object = <Shape extends Record<string, Schema<unknown>>>(
  shape: Shape,
): Schema<{ [K in keyof Shape]: Infer<Shape[K]> }> => ({
  parse: (x, path = "") => {
    if (typeof x !== "object" || x === null || Array.isArray(x)) return fail(path, "an object", x);
    const out: Record<string, unknown> = {};
    for (const [key, schema] of Object.entries(shape)) {
      const r = schema.parse((x as Record<string, unknown>)[key], path ? `${path}.${key}` : key);
      if (!r.ok) return r;
      out[key] = r.value;
    }
    return ok(out as { [K in keyof Shape]: Infer<Shape[K]> });
  },
});

// ---------- 2. The domain: the schema is the single source of truth for the Order type ----------
const OrderSchema = object({
  id: string(),
  customer: object({ name: string(), tier: oneOf("standard", "member", "wholesale") }),
  lines: array(object({ sku: string(), qty: integer(1, 999), unitCents: integer(1, 1_000_000) }), 1),
});
type Order = Infer<typeof OrderSchema>;
type Tier = Order["customer"]["tier"];

type Discount =
  | { kind: "none" }
  | { kind: "percent"; percent: number }
  | { kind: "bulk"; minQty: number; percent: number };

const DISCOUNTS = {
  standard: { kind: "none" },
  member: { kind: "percent", percent: 5 },
  wholesale: { kind: "bulk", minQty: 20, percent: 12 },
} as const satisfies Record<Tier, Discount>;

function discountCents(discount: Discount, subtotal: number, totalQty: number): number {
  switch (discount.kind) {
    case "none":
      return 0;
    case "percent":
      return Math.round((subtotal * discount.percent) / 100);
    case "bulk":
      return totalQty >= discount.minQty ? Math.round((subtotal * discount.percent) / 100) : 0;
  }
}

interface Invoice {
  readonly orderId: string;
  readonly customer: string;
  readonly subtotalCents: number;
  readonly discountCents: number;
  readonly totalCents: number;
}

function price(order: Order): Invoice {
  const subtotal = order.lines.reduce((sum, l) => sum + l.qty * l.unitCents, 0);
  const qty = order.lines.reduce((sum, l) => sum + l.qty, 0);
  const discount = discountCents(DISCOUNTS[order.customer.tier], subtotal, qty);
  return {
    orderId: order.id,
    customer: order.customer.name,
    subtotalCents: subtotal,
    discountCents: discount,
    totalCents: subtotal - discount,
  };
}

// ---------- 3. The program: data arrives as unknown, exactly as from fetch or a file ----------
const submissions: unknown = JSON.parse(`[
  {"id": "A-100", "customer": {"name": "Zanele", "tier": "member"},
   "lines": [{"sku": "rooibos", "qty": 3, "unitCents": 450}, {"sku": "honey", "qty": 1, "unitCents": 1200}]},
  {"id": "A-101", "customer": {"name": "Kenji", "tier": "wholesale"},
   "lines": [{"sku": "matcha", "qty": 25, "unitCents": 900}]},
  {"id": "A-102", "customer": {"name": "Luis", "tier": "vip"},
   "lines": [{"sku": "yerba", "qty": 2, "unitCents": 650}]},
  {"id": "A-103", "customer": {"name": "Amina", "tier": "standard"},
   "lines": [{"sku": "hibiscus", "qty": 0, "unitCents": 300}]},
  {"id": "A-104", "customer": {"name": "Olga", "tier": "standard"},
   "lines": [{"sku": "chai", "qty": 4, "unitCents": 525}]}
]`);

const money = (cents: number) => (cents / 100).toFixed(2).padStart(8);
const list = Array.isArray(submissions) ? submissions : [];
const invoices: Invoice[] = [];

for (const [i, raw] of list.entries()) {
  const parsed = OrderSchema.parse(raw, `orders[${i}]`);
  if (!parsed.ok) {
    console.log(`rejected  ${parsed.error}`);
    continue;
  }
  invoices.push(price(parsed.value));
}

for (const inv of invoices) {
  console.log(`${inv.orderId}  ${inv.customer.padEnd(7)}${money(inv.subtotalCents)}${money(-inv.discountCents)}${money(inv.totalCents)}`);
}
const grand = invoices.reduce((sum, inv) => sum + inv.totalCents, 0);
console.log(`${invoices.length} invoices, ${list.length - invoices.length} rejected, total ${money(grand).trim()}`);

export {};
text
rejected  orders[2].customer.tier: expected standard | member | wholesale, got "vip"
rejected  orders[3].lines[0].qty: expected an integer from 1 to 999, got 0
A-100  Zanele    25.50   -1.28   24.22
A-101  Kenji    225.00  -27.00  198.00
A-104  Olga      21.00    0.00   21.00
3 invoices, 2 rejected, total 243.22

How it fits together

The schema library (part 1). A Schema<T> is any object with a parse method that turns unknown into a Result<T>, the discriminated union from lesson four. The builders string, integer, oneOf, array and object create schemas, and object composes them. Infer<S> is a conditional type with infer that reads T back out of a Schema<T>, and object's return type is a mapped type that applies Infer to each property. oneOf uses a const type parameter (lesson six), so oneOf("standard", "member", "wholesale") produces a schema of exactly that union. Error messages carry a path (orders[3].lines[0].qty), the kind of detail that makes a rejected request easy to fix.

The domain (part 2). type Order = Infer<typeof OrderSchema> is the payoff: the compiler computes

text
{ id: string; customer: { name: string; tier: "standard" | "member" | "wholesale"; }; lines: { sku: string; qty: number; unitCents: number; }[]; }

(as revealed by assigning an Order to a variable of type never), and nobody wrote it by hand. Tier is an indexed access into it. The discounts are a discriminated union, and DISCOUNTS is checked with satisfies Record<Tier, Discount>, so the table must cover every tier. Add "partner" to the oneOf and forget the table, and the compiler reports Property 'partner' is missing in type ... at the table, before any order is mispriced. discountCents switches on the discriminant with no default, relying on its number return type for exhaustiveness. Money is kept in integer cents throughout, as the JavaScript course recommended, and Invoice's fields are readonly.

The program (part 3). The submissions are unknown, exactly as they would be from fetch or a file. Each one is parsed; failures are reported with their path and skipped; successes are priced. Inside price, no check is needed for anything the schema already guaranteed: a quantity is a positive integer, a tier is one of three strings.

Strictness. The program compiles not only with --strict, as this course's checker runs it, but also with noUncheckedIndexedAccess, exactOptionalPropertyTypes, noImplicitOverride, noImplicitReturns, noFallthroughCasesInSwitch, verbatimModuleSyntax and moduleDetection: force. Iterating with Object.entries instead of indexing shape[key] is what made it pass the first of those.

Extending it

Good next steps, each exercising a different lesson: add an optional(schema) builder and make customer.email optional (watch how exactOptionalPropertyTypes affects the mapped type); collect all errors in an order instead of stopping at the first; add a "partner" tier with a fixed discount per line, as a new member of the Discount union; split the file into modules (schema.ts, orders.ts, main.ts) with import type where appropriate; write type-level tests with Equal and Expect for Infer; and replace the hand-made schema library with Zod, comparing how much code disappears.

Further reading

Where to go next

  • Read the handbook end to end, now that you know what each part is for, and keep the TSConfig reference nearby when setting up projects.
  • Follow the release notes. Each TypeScript release explains its new features with examples; the blog posts for 6.0 and 7.0 describe the new defaults and the native compiler. Use the Playground to try every example.
  • Read well-typed code. The type declarations of libraries you use (open them from your editor with "go to definition") are a free course in practical type design.
  • Practise type-level thinking in moderation. Collections of type challenges exist online and are good puzzles, but the skill that matters at work is modelling data clearly, deriving types from a single source, and keeping any and assertions at the edges.
  • Pick a framework and build something: a React or Vue front end, a typed API with a Node framework, or both sharing one set of types.
Common misconceptionsH

Common misconceptions

Misconception

"Strict mode is for experts; beginners should start loose." The opposite: without strict null checks and noImplicitAny, TypeScript misses most of the bugs beginners make. Start strict, which TypeScript 6.0 and later do by default.

Misconception

"Migrating to TypeScript means rewriting the project." It means renaming files and adding types, gradually, with allowJs and checkJs letting JavaScript and TypeScript coexist for as long as needed. Behaviour doesn't change, because the emitted JavaScript is the same code.

Misconception

"With TypeScript, run-time validation is redundant." Types describe what your code assumes; validation checks that the outside world agrees. You need both, and a schema library gives you both from one definition.

Misconception

"// @ts-ignore and // @ts-expect-error are the same." @ts-expect-error reports an error when there is no longer anything to suppress, so it cannot silently outlive the problem it was hiding. Prefer it, with a comment explaining why.

Exercises

Exercises

The last few exercises are about the project: run it, change it, and check your predictions.

1. TypeScript in practice

Warm-upComputational

Which of these lines are errors under --strict but compile when strict is off? Choose all that apply.

Choose all that apply

2. TypeScript in practice

CoreComputational

With noUncheckedIndexedAccess on, what is the type of x in const arr: number[] = [1]; const x = arr[0];?

3. TypeScript in practice

CoreComputational

Using the lesson's median, what does console.log(median([2, 8, 4]), median([10, 20])) print?

4. TypeScript in practice

CoreHuman

During a migration you must leave one known type error in place for now. Why do experienced teams write // @ts-expect-error with a reason, rather than // @ts-ignore?

Choose one

5. TypeScript in practice

CoreComputational

In the project, what message does OrderSchema.parse({ id: "B-1", customer: { name: "Ife", tier: "member" }, lines: [] }, "orders[0]") produce?

6. TypeScript in practice

CoreComputational

In the project, a wholesale customer orders 20 units of one product at 500 cents each. What is totalCents on the invoice?

7. TypeScript in practice

StretchHuman

In a typed web application, where should run-time validation of incoming data happen?

Choose one

Further reading and resources