Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·16

TypeScript

Companion to Volume 2, chapter 16: how the basics, describing values and type-level programming connect; new angles (the checker as a building inspector who leaves before anyone moves in, unions as a menu with a fixed list, generics as a tiffin carrier sized by what goes in, the boundary as customs); what the chapter simplifies, measured with tsc 5.9: a narrowing that survives `await` (the order was placed meanwhile) but not a callback, a `readonly` price changed through another type, a union too complex to represent, and `skipLibCheck` turning a broken generated type into `any`; the theory behind it; how TypeScript's own `lib.es5.d.ts` defines `Pick`, `Omit` (which accepts typos), `JSON.parse` and `Object.keys`; four debugging drills; interview questions with how to approach each.

6 sections · ~17 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 16 has three strands. The basics: a checker that erases itself, annotations and inference, structural typing and brands, the strict options, and the escape hatches. Describing values: unions and literal types, narrowing, discriminated unions, generics with constraints, and variance, where soundness ends. Type-level programming and the boundary: keyof and indexed access, mapped and utility types, conditional types and infer, declaration files, and runtime validation for data from outside.

the basics describing values types of types, and the boundary a checker that erases types gone at run time annotations, inference say less, know more structural typing shape, not name branded types names for shapes strict options null · any · indexes escape hatches any · as · ! unions, literals one of these values narrowing typeof · in · guards discriminated unions a tag per case generics types as parameters constraints extends keyof T variance where soundness ends keyof, indexed access types from types mapped, utility types Partial · Pick · Omit conditional, infer types that branch declarations .d.ts · merging runtime validation schemas at the edge tsconfig, speed checks have a budget checks by tightened by plus except split by clearest with plus bounded by raises feeds plus published in checked by configured by goes deeper: Vol 1 ch5 types in Java · ch15 JavaScript · ch19 the API client · Vol 3 the Java contract exercises: P1–P10 strict options, branding, exhaustive unions, variance, type-level tests, Zod
Concept map of chapter 16, TypeScript: the basics (a checker that erases itself, annotations and inference, structural typing, strict options), describing values (unions and literals, narrowing, discriminated unions, generics and constraints, variance) and type-level programming and the boundary (keyof and mapped types, conditional types and infer, declarations, runtime validation), with links such as narrowing turning a union into one member and types disappearing at run time, so data from outside needs a runtime check.

The links worth remembering:

  • Types are a claim, checked once, then erased. Everything the checker proves is about the code as written, with the data it can see. Data that arrives at run time (JSON, storage, messages from workers) hasn't been checked by anyone until your code checks it.
  • Narrowing is the checker following your ifs. It's what makes unions usable, and it's also where the checker makes assumptions about time that JavaScript doesn't keep (Gaps 1).
  • The strictness you get is the strictness you configure. strict is a starting point; noUncheckedIndexedAccess, exactOptionalPropertyTypes and skipLibCheck: false close holes that strict leaves (Gaps 4).

Explain it differently

1. The checker is a building inspector who leaves before anyone moves in. It reads the plans (your source) carefully, signs them off, and goes home. What happens once people live there (JSON from the server, values from localStorage, a library's actual behaviour) is nobody's job unless you hire a guard at the door: a runtime check.

2. A union type is a menu with a fixed list. 'Placed' | 'Ready' | 'Delivered' means an order's status is exactly one of these and nothing else. Narrowing is the waiter asking "which one?" before bringing the plate. A discriminated union puts the answer on a tag (kind), so one question tells you everything else about the order.

3. Structural typing is "if it fits the slot, it's accepted". TypeScript doesn't care what a value is called, only what shape it has. A Weight of { grams: number } fits wherever a { grams: number } is expected, even if you meant only Rice. Brands are a notch cut into the shape so only the right key fits.

4. Generics are a tiffin carrier sized by what goes in. Box<T> is one carrier design; Box<Idli> and Box<Dosa> are the same carrier with a label saying what's inside. Constraints (T extends { id: string }) are "only food that comes with a token number".

5. any is a "pass without inspection" stamp, and it spreads. A value typed any can go anywhere, and whatever you take out of it is any too. One JSON.parse result passed around unchecked stamps every value it touches. unknown is the opposite stamp: "must be inspected before use".

6. Mapped types are a mail merge for types. { [K in keyof Dish]: … } takes a template and fills it in once per key. Partial, Readonly and Record are mail merges in TypeScript's own standard library, a few lines each (Code walkthrough).

7. Declaration files are a restaurant's menu card, not its kitchen. A .d.ts promises what a library offers, and the checker believes the card. If the card lists a dish the kitchen can't make, nothing tells you until you order it (Gaps 4).

8. Variance is about which way a pipe flows. A pipe that only delivers dosas (a producer, () => Dosa) can be used where any food is expected. A bin that only accepts dosas (a consumer, (d: Dosa) => void) can't be used where someone will drop in idlis. Arrays are both pipe and bin, which is why mutable arrays can't be both safe and convenient.

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from TypeScript 5.9.3 (tsc --strict) and Node 22.

1. "Narrowing is dropped where the value might change": in callbacks, but not across await. Chapter Exercises T4 notes that a narrowed property isn't trusted inside a callback. The same reasoning applies to await, and the checker doesn't apply it:

TypeScript
if (cart.status === 'open') {
  await save();
  const s: 'open' = cart.status;                        // the checker still believes 'open' after the await
  ...
}
function addLater(item: string) {
  if (cart.status === 'open') {
    setTimeout(() => { const s: 'open' = cart.status; }, 0);   // in a callback, the narrowing is dropped
  }
}
Terminal
await.ts(16,30): error TS2322: Type '"open" | "placed"' is not assignable to type '"open"'.
  Type '"placed"' is not assignable to type '"open"'.

Only the callback line is an error. With it removed, the file compiles, and running it (another part of the app places the order during the save):

Terminal
after await, the checker says open; at run time status is "placed"

Every await is a point where other code runs (the Companion to chapter 15, theoretical gap 2), but control-flow analysis treats an async function as if it ran straight through. It's a deliberate trade-off (invalidating every narrowing at every await and function call would make the checker unusable), and a real hole: re-read shared state after an await before relying on it (drill D1).

2. "readonly stops writes": through that type only. Arrays are checked, plain objects aren't:

TypeScript
type Price = { readonly paise: number };
type Editable = { paise: number };
const fixed: Price = { paise: 8950 };
const handle: Editable = fixed;                           // readonly isn't checked when assigning to a mutable type
handle.paise = 1;
Terminal
fixed.paise after writing through another type: 1
readonly.ts(8,7): error TS4104: The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.

The object assignment compiles and the "fixed" price changes; the array assignment (line 8, uncommented for the second run) is rejected. readonly on a property is a promise about this view of the object, not about the object, and assignability ignores it for properties. For values that must not change, freeze them (Object.freeze) or copy them at the boundary (drill D2).

3. Type-checking speed: types have a budget. The chapter shows template literal types. They multiply: a key type for kitchen × time slot × dish:

TypeScript
type Key2 = `${Kitchen}/${Slot}/${Dish}`;                    // 12 × 64 × 10 = 7,680 members: fine
type Key3 = `${Kitchen}/${Slot}/${Dish}/${Qty}`;             // 12 × 64 × 30 × 10 = 230,400
Terminal
b.ts(5,13): error TS2590: Expression produces a union type that is too complex to represent.

TypeScript caps unions at 100,000 members. Below the cap, size still costs: a Record over the 7,680 keys plus a mapped type derived from it raised Check time from 0.76 s to 1.13 s (--extendedDiagnostics) in a file that's otherwise empty, and every file that uses those types pays again. Keys built from data (kitchens, slots, dishes) belong in string with a runtime check, not in the type system (drill D3).

4. skipLibCheck doesn't just skip libraries: it lets a broken declaration become any. Most project templates set skipLibCheck: true for speed. It skips all .d.ts files, including your own generated ones. A generated api.d.ts that forgot to emit Money:

TypeScript
export interface Dish { id: string; name: string; price: Money }   // api.d.ts
const label: string = d.price.toUpperCase();                        // use.ts: price is supposed to be Money { paise: number }
Terminal
== skipLibCheck: false
api.d.ts(2,58): error TS2304: Cannot find name 'Money'.
exit 2
== skipLibCheck: true
exit 0

With the check skipped, the unresolved Money becomes an error type that behaves like any, so d.price.toUpperCase() compiles, and crashes at run time. Keep skipLibCheck: false for projects whose .d.ts files you generate, or check generated declarations in a separate step (drill D4).

Common misconceptions

Misconception What's actually true Where it's shown
"Narrowing is reset whenever the value could change." In callbacks, yes; across await and function calls, no. Gaps 1; drill D1
"readonly makes a property immutable." Only through that type; an alias with a mutable type can write it. Gaps 2; drill D2
"The type system can model any set of strings." Unions are capped at 100,000 members, and large ones slow every check. Gaps 3; drill D3
"skipLibCheck only skips node_modules." It skips every .d.ts, and broken declarations become any. Gaps 4; drill D4
"Omit<T, 'x'> checks that x exists." Omit accepts any key, so typos compile; Pick checks. Code walkthrough
"Typed JSON is checked JSON." JSON.parse returns any; nothing checks it unless you do. Code walkthrough; Explain it differently 1

Theoretical gaps: the ideas behind the chapter

1. Soundness is a design choice, and TypeScript chose not to have it. A sound type system guarantees that a well-typed program never has a type error at run time. TypeScript's stated goal is to be useful for existing JavaScript, which means accepting unsound rules where sound ones would reject common correct code: covariant arrays, bivariant methods, narrowings that survive await, readonly that doesn't affect assignability, any. Knowing the list is part of using the tool well.

2. Gradual typing makes the boundary explicit. Typed and untyped code coexist, and the places where they meet (any, JSON, .d.ts files, casts) are where guarantees end. The research on gradual typing (Siek and Taha; "Typed Racket") shows that sound gradual systems need runtime checks at those boundaries; TypeScript doesn't insert them, so your code must (Explain it differently 1, 5).

3. Structural typing is subtyping by shape. A type is a set of values; { a: number; b: string } is a subset of { a: number } (more constraints, fewer values), so it's assignable to it. That's why excess properties are allowed except in fresh literals, why brands are needed to separate equal shapes, and why Java's nominal intuition ("a Weight is not a Money") doesn't transfer.

4. Types are a lattice. unknown is the top (every value), never the bottom (no values); unions are joins, intersections are meets. any is outside the lattice: both top and bottom at once, which is exactly why it disables checking. Many puzzles (why keyof (A | B) has fewer keys than keyof A, why T & never is never) are lattice arithmetic.

5. The type checker is a program, with a cost model. Conditional and recursive types are a small functional language evaluated at compile time; each instantiation is computed and cached. Complexity in types costs editor responsiveness and CI time, and has hard limits (on instantiation depth, and on unions, at 100,000 members). Type-level cleverness should be paid for by what it prevents (Gaps 3).

6. Erasure keeps JavaScript the source of truth. TypeScript's output is the input minus types, so runtime behaviour never depends on types: no overloading by type, no reflection on generics, no runtime type checks. The erasableSyntaxOnly option and Node's built-in type stripping push this further, rejecting the few features (enums, namespaces with values, parameter properties) that emit code. It's the opposite design from Java, where generics are erased but classes and interfaces exist at run time.

Applying it

Code walkthrough

TypeScript's standard library types are ordinary TypeScript, in node_modules/typescript/lib/lib.es5.d.ts (TypeScript 5.9.3). Reading them answers questions the chapter only states.

Utility types are a few lines each

TypeScript
/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};

/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

/**
 * Exclude from T those types that are assignable to U
 */
type Exclude<T, U> = T extends U ? never : T;

/**
 * Construct a type with the properties of T except for those in type K.
 */
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

Partial is a mapped type with ? added; Pick maps over the chosen keys; Exclude is a conditional type that distributes over a union, dropping members. Omit is built from both. Note the constraints: Pick<T, K extends keyof T> but Omit<T, K extends keyof any>. keyof any is string | number | symbol, so Omit accepts any key, including one that isn't in T. Real tsc output on Dish with a typo in each:

TypeScript
type NewDish = Omit<Dish, 'pirce'>;                     // typo: compiles; nothing is removed
type Card = Pick<Dish, 'name' | 'pirce'>;               // typo: error
Terminal
w.ts(3,24): error TS2344: Type '"name" | "pirce"' does not satisfy the constraint 'keyof Dish'.
  Type '"pirce"' is not assignable to type 'keyof Dish'.

Line 2 produced no error. The loose constraint was deliberate (Omit is often used with keys that only some union members have), but it means Omit<Dish, 'pirce'> silently keeps pricePaise. A strict version is one line: type StrictOmit<T, K extends keyof T> = Omit<T, K>.

The JavaScript built-ins, as typed

TypeScript
    keys(o: object): string[];
    ...
    parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
    ...
    filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];
    filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];

Object.keys returns string[], not (keyof T)[], because of structural typing: an object of type Dish may have more properties at run time than Dish declares (theoretical gap 3), so claiming the keys are exactly keyof Dish would be a lie. JSON.parse returns any, which is why typed code can be quietly untyped right after a fetch. filter has two overloads: with a type-predicate callback (x is S) the result narrows to S[]; otherwise it stays T[] (since 5.5, TypeScript also infers simple predicates like x => x !== undefined). Real output:

TypeScript
for (const k of Object.keys(d)) console.log(d[k]);      // keys are string, not keyof Dish
const parsed: Dish = JSON.parse('{"id": 7}');            // any: accepted without a check
Terminal
w.ts(6,45): error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ id: string; name: string; pricePaise: number; veg: boolean; }'.

The Object.keys loop is rejected; the JSON.parse line, assigning {"id": 7} to a Dish, isn't.

Read it yourself

  1. Read Awaited<T> in the same file. Why does it check for a callable then instead of T extends Promise<infer U>?
  2. Why is ReturnType declared as type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;, with an any at the end, if the constraint already guarantees a function?

Debugging drills

D1. Items added to a placed order

The cart code checks that a cart is open before adding an item, and the type says so. Production logs show items added to carts that were already placed, a few times a day, always when the network was slow.

TypeScript
async function addItem(cart: Cart, item: Line) {
  if (cart.status !== 'open') return;
  await api.saveDraft(cart);              // 300 ms on a slow network
  cart.lines.push(item);                  // cart.status is 'open' here, says the checker
}

D2. The menu price changed by itself

The menu module exports dishes typed { readonly pricePaise: number }. After a promotion runs, the menu shows the promotional price everywhere, even after the promotion ends. The promotion code:

TypeScript
function applyPromo(lines: { pricePaise: number }[], percent: number) {
  for (const l of lines) l.pricePaise = Math.round(l.pricePaise * (100 - percent) / 100);
}
applyPromo(cart.lines.map(l => l.dish), 10);

D3. Type-checking went from 40 s to 6 minutes

After a pull request that added typed route keys for the kitchen scheduler, CI's type-check step takes six minutes and editors lag on every keystroke in the scheduler files. The new types:

TypeScript
type Slot = `${Hour}:${Minute}`;                       // 16 × 4
type SlotKey = `${KitchenId}/${Slot}/${DishId}`;       // KitchenId and DishId generated from the database: 40 and 300 members
type Schedule = { [K in SlotKey]?: number };

D4. "Cannot read properties of undefined (reading 'toUpperCase')", in typed code

The receipt page crashes on d.price.toUpperCase(). Everyone agrees price is an object with paise, and that this line should never have compiled. tsc passes in CI. The types come from a generated api.d.ts.

Career-oriented

Interview prep

Mid level

Q1. What's the difference between const routes: Record<string, Route> = {...} and const routes = {...} satisfies Record<string, Route>?

How to get there. Compare what type the variable ends up with in each case, and what that means for later uses (autocompletion of keys, typos when reading).

Q2. Write a helper so that for (const k of keysOf(dish)) gives k: keyof Dish. Then explain when it's wrong.

How to get there. The helper is a one-line cast. The interesting part is the second half: why does the standard library refuse to do this (Code walkthrough)?

Senior level

Q3. tsc takes 90 seconds in CI and editors are slow in a 400,000-line frontend. What do you do?

How to get there. Chapter Exercises leaves checking speed out. Measure first (which projects, which files, which types), then structural fixes (project references, incremental builds), then type-level fixes, then the trade-offs you refuse (turning checks off).

Q4. Design how the TiffinBox API client reports failures: exceptions, or a result type like { ok: true, value } | { ok: false, error }?

How to get there. Consider which failures are expected (validation errors, 404, 409 conflict) and which are bugs (contract violations), what the caller must handle, and what TypeScript can enforce. Look at what the stage 16 client does.

Staff level

Q5. Set the policy on "when not to use TypeScript features" for TiffinBox's frontend teams.

How to get there. Chapter Exercises leaves this out. Group features by their costs: features that emit code (and aren't erasable), features that weaken checking, and type-level features whose complexity costs more than it prevents. For each, give a rule and an enforcement mechanism.

Q6. Mobile (Kotlin) and the web (TypeScript) both consume the TiffinBox API, and the Java team changes it weekly. How do you keep three languages in agreement without slowing the backend team down?

How to get there. Chapter Exercises S4 covers sharing types between Java and TypeScript. This is about evolution: one source of truth, generated code per language, checks that run on every change, and rules for what counts as a breaking change.