Workbench / Volume 2 Exercises: The Web Frontend
V2·16
TypeScript
Exercises for Volume 2, chapter 16: TypeScript as an erasing type checker, the essential compiler options (strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes), primitive and special types (any, unknown, never), interfaces and type aliases, structural typing and branded types, unions, literal types, narrowing and discriminated unions, intersections, generics, constraints and variance, type-level programming (keyof, indexed access, mapped, utility, conditional and template literal types, infer, recursive types), declaration files, merging and module augmentation, and the gap between compile-time types and runtime validation (Zod, Valibot, JSON Schema). 10 theory questions, 10 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. TypeScript exercises have two kinds of output: compiler errors (npx tsc --noEmit) and runtime behaviour (node --experimental-transform-types file.ts, or tsx). Both kinds of output in the solutions are real: TypeScript 5.9 with this tsconfig.json, and Node 22:
{ "compilerOptions": { "target": "es2022", "module": "nodenext", "strict": true,
"noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": true, "noEmit": true, "skipLibCheck": true } }
As a Java developer, expect two surprises throughout: TypeScript's types are structural (shape matters, not names), and they disappear at run time (nothing checks data from the network unless you add a runtime validator).
Coverage map.
| Chapter component | Exercises |
|---|---|
| a checker that erases itself; compiler options | T1, P1, P9 |
| primitive and special types: any, unknown, never | T2, P1 |
| interfaces vs type aliases; structural typing; excess property checks | T3, P2 |
| branded types (nominal typing on purpose) | T3, P3 |
| unions, literal types, narrowing, discriminated unions, exhaustiveness | T4, P4 |
| intersections | T4 |
| generics, constraints | T5, P5 |
| variance | T6, P6 |
| keyof, indexed access, mapped and utility types | T7, P7 |
| conditional types, infer, template literal and recursive types | T8, P7 |
| declaration files, merging, module augmentation | T9, P8 |
| compile-time safety vs runtime validation (Zod and friends) | T10, P9, P10 |
Theory
T1. What TypeScript is (and isn't)
- TypeScript is described as "JavaScript plus a type checker that erases itself". What does
tscdo with types when it emits JavaScript, and what does that mean for performance, debugging and runtime behaviour? - P9's run of a
.tsfile with Node's strip-only mode failed withTypeScript enum is not supported in strip-only mode. Which TypeScript features generate code (enums, namespaces, parameter properties, decorators with metadata), why do new tools prefer "erasable syntax only", and what do you use instead of enums? - Explain
strict(and what it turns on),noUncheckedIndexedAccessandexactOptionalPropertyTypes, with the bug each prevents (P1 shows three of them).
T2. any, unknown and never
- Compare
any,unknownandnever. P1:let u: unknown = JSON.parse(…); u.awas an error ('u' is of type 'unknown'), whilelet a: any = JSON.parse(…); a.b.c.d()compiled. Why isany"contagious", and where does it sneak in (JSON.parse, untyped libraries,catchvariables in older settings)? - What is
never, and what are its three main uses (exhaustiveness checks, impossible states, functions that never return)? - What's the difference between
object,{},ObjectandRecord<string, unknown>?
T3. Structural typing and branded types
- P2: passing a variable with an extra
spicyproperty toshow(d: Dish)compiled, but passing the same object as a literal failed with "Object literal may only specify known properties". Explain structural typing and the excess-property check, and how this differs from Java's nominal typing. - When do you use
interfaceversustype? Mention declaration merging, extends vs intersections, and unions. - P3: with
type Paise = number & { readonly __brand: 'Paise' }andtype Rupees = number & { readonly __brand: 'Rupees' }, passing aRupeestocharge(p: Paise)failed. Explain branded types and give three uses in TiffinBox (money units, IDs of different entities, validated strings).
T4. Unions, narrowing and discriminated unions
- Model TiffinBox's order status as a discriminated union (P4: placed, paid with an amount, delivered with a time, cancelled with a reason) and explain why it's better than one interface with optional fields (
status: string; amountPaise?: number; deliveredAt?: string; reason?: string). - List the ways TypeScript narrows:
typeof,instanceof,in, equality and truthiness, discriminant checks, user-defined type guards (x is T), assertion functions (asserts x is T), and control-flow analysis. Where does narrowing get lost (callbacks, after awaits on mutable properties)? - What's an intersection type (
A & B), when is it useful, and when does it collapse tonever?
T5. Generics and constraints
- Write a generic
pluck<T, K extends keyof T>(items: T[], k: K): T[K][](P7 used it) and explain each part. Why didpluck([dish], 'price')fail with "Argument of type '"price"' is not assignable to parameter of type 'keyof Dish'"? - Write a typed
groupBy<T, K extends PropertyKey>(items: T[], key: (t: T) => K): Record<K, T[]>, and a genericResult<T, E>type withok/errhelpers. When are generics overkill? - Compare TypeScript generics with Java's: erasure in both, but structural constraints, inference from arguments, generic defaults, and no runtime
T.
T6. Variance and soundness
- P6:
const dogs: Dog[] = [new Dog()]; const animals: Animal[] = dogs; animals.push(new Cat());compiled, anddogs.forEach(d => d.bark())crashed withd.bark is not a function. Explain covariance, why mutable arrays should be invariant, and why TypeScript allows it anyway. How does Java handle the same case (arrays vs generics)? - What does
strictFunctionTypescheck, and why are method parameters still checked "bivariantly"? - Name three other places where TypeScript is deliberately unsound, and how you protect yourself.
T7. keyof, indexed access, mapped and utility types
- Using P7's
Dish(id,name,pricePaise,veg, optionaltags), state the result of:keyof Dish,Dish['pricePaise'],Pick<Dish, 'id' | 'pricePaise'>,Partial<Omit<Dish, 'id'>>,Readonly<Dish>(P7: assigningrd.namefailed),Required<Dish>,Record<'veg' | 'nonveg', Dish[]>,ReturnType<typeof fetchMenu>,Awaited<ReturnType<typeof fetchMenu>>,Parameters<typeof placeOrder>. - Write a mapped type
Getters<T>that turns{name: string}into{getName: () => string}using key remapping (as) andCapitalize. P7 verified it at compile time. - Why do API types usually come in several variants (create request, update request, response, list item), and how do utility types help derive them from one source?
T8. Conditional, infer, template literal and recursive types
- Explain
T extends U ? X : Y, distribution over unions, andinfer. WriteElementType<T>(P7:ElementType<Dish[]>=Dish) and a recursiveUnwrap<T>for nested promises (P7:Unwrap<Promise<Promise<number>>>=number). - P7 defined a recursive
Jsontype and rejected{ d: new Date() }. Write it and explain whyDateisn't JSON. - P9 typed routes as
`/kitchens/${number}` | `/orders/${string}`. Give two more uses of template literal types (event names, CSS units, i18n keys), and say when type-level programming is going too far.
T9. Declarations, merging and augmentation
- What's a
.d.tsfile, where do types for npm packages come from (bundled,@types/*from DefinitelyTyped, none), and what do you do for an untyped package? - Explain declaration merging and module augmentation with two real cases: adding a property to
Window(window.dataLayerfor analytics), and adding a field to a library's request type (Express'sRequest.user, or a router's route metadata). - Why should you avoid
declare module 'x'with everything asany, and what's a safer minimal declaration?
T10. Types versus runtime validation
- P9:
JSON.parse('{"id": 42, "totalPaise": "22900", "items": null}') as Ordercompiled; at run timetypeof o.idwasnumber,o.totalPaise + 100was "22900100" (string concatenation), ando.items.mapcrashed far from the cast. Explain why types can't protect you here, and where data enters a frontend untyped. - P9 validated the same JSON with Zod: three errors (
id: Expected string, received number,totalPaise: Expected number, received string,items: Expected array, received null), andz.inferproduced the static type. Compare Zod/Valibot/ArkType with JSON Schema and OpenAPI-generated types. Where should validation happen, and how strict should it be (unknown fields, coercion)? - How do you keep frontend types in sync with a Java backend (Volume 3)?
Programming exercises
P1. The strict options, felt
Create the tsconfig above and a file with: function len(s: string | null) { return s.length; }; const names: string[] = ['dal']; const first: string = names[0];; interface Opt { note?: string } const o: Opt = { note: undefined };; let u: unknown = JSON.parse('{"a":1}'); u.a;; and let a: any = JSON.parse('{"a":1}'); a.b.c.d();. Run npx tsc -p . and read every error. Then turn strict off and see which errors disappear, and fix each properly with strict on.
P2. Structural typing and excess properties
With interface Dish { id: string; name: string; pricePaise: number; veg: boolean } and function show(d: Dish): pass an object with an extra spicy property from a variable, then as a literal; then misspell pricePaise as pricepaise in a literal, and in a variable. Then define interface Review { id: string; name: string; pricePaise: number; veg: boolean } (same shape, different meaning) and show that a Review can be passed to show without complaint.
P3. Brand your money and IDs
Define Paise, Rupees, OrderId and KitchenId as branded types, with constructor functions that validate (toPaise rejects non-integers and negatives; orderId checks a pattern). Write charge(amount: Paise) and cancelOrder(id: OrderId), and show that passing Rupees or a KitchenId fails to compile. Then show how the brand interacts with arithmetic (a + b gives a plain number) and write addPaise(a: Paise, b: Paise): Paise.
P4. A discriminated union with exhaustive handling
Model OrderStatus as T4's union and write label(s: OrderStatus): string with a switch and a never default. Leave out the cancelled case and read the compiler error. Then write canCancel(s), a type guard isPaid(s): s is Extract<OrderStatus, {kind: 'paid'}>, and a reducer next(s, event) for transitions (placed → paid → delivered; placed or paid → cancelled) that rejects invalid transitions at compile time where possible and at run time otherwise.
P5. Generic utilities
Implement and type: pluck<T, K extends keyof T>(items: T[], k: K): T[K][]; groupBy<T, K extends PropertyKey>(items, key); Result<T, E> with ok, err and a tryAsync(fn) that converts a rejected promise into a Result; and a memoize<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R. Write a call that misspells a key for pluck and read the error. Add compile-time tests with Expect<Equal<…>>.
P6. Variance holes
Reproduce P6's covariant-array hole (Dog[] assigned to Animal[], a Cat pushed, a crash calling bark). Then make the function that pushes take readonly Animal[] and see the push become a compile error. Then compare a callback declared with method syntax and with property syntax under strictFunctionTypes, passing a handler that expects a Dog where an Animal handler is required.
P7. Type-level programming with tests
Using Dish, write and test with Expect<Equal<…>>: keyof Dish; Getters<T> with key remapping; ElementType<T> with infer; a recursive Unwrap<T> for nested promises; Partial<Omit<Dish, 'id'>>; a recursive Json type that rejects Date; and Readonly<Dish> (try to assign a property). Then write DeepReadonly<T> and test it on a nested order type.
P8. Declarations for an untyped library and a global
Write (a) a global.d.ts that adds dataLayer: unknown[] and __APP_VERSION__: string to Window/globals, (b) a minimal declare module 'legacy-maps' for a pretend untyped library with createMap(el, options), and (c) a module augmentation that adds a typed meta: { requiresAuth: boolean } to a router library's route type (use a small local "library" module to simulate). Show what happens if you instead write declare module 'legacy-maps';.
P9. When types lie at run time
Run P9's script: parse {"id": 42, "totalPaise": "22900", "items": null} with as Order, print typeof o.id, compute o.totalPaise + 100, and call o.items.map. Then run it with node --experimental-strip-types and with an enum added, and note the error; switch to --experimental-transform-types (or tsx) and print the enum object. Finally, write a user-defined type guard isOrder(x: unknown): x is Order by hand and compare its length and coverage with a Zod schema (P10).
P10. Validate the API boundary with Zod
Write a Zod schema for the order response with branded IDs and paise (z.string().regex(…).transform(s => s as OrderId), z.number().int().nonnegative().transform(n => n as Paise)), an ISO date string transformed into a Date (or kept as a string with .datetime({ offset: true })), and a nested items array. Validate the bad JSON from P9 and print the issues with paths; validate a good one and use z.infer. Then plug the schema into chapter 15's API client so every response is validated, and report validation failures to the console as if to an error tracker, with the request URL.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–16)
C1. A typed, generated API layer for TiffinBox
Write a small OpenAPI 3.1 spec for three endpoints (GET /kitchens/{id}/menu, POST /orders, GET /orders/{id}) with IDs as strings, money as integer paise, ISO timestamps with offsets, and a discriminated status. Generate TypeScript types with openapi-typescript and write a typed client wrapper around chapter 15's request so that paths, parameters and responses are all type-checked (a wrong path or missing parameter fails compilation). Add runtime validation of responses (generated or hand-written Zod schemas), and a CI script that regenerates types and fails if they changed without a commit.
Combines: CLI tooling and exit codes (Vol 1 ch 01); API contracts and JSON number rules (ch 06, 09); parsing and code generation (ch 10); this volume's fetch, URLs and security (ch 12–15) and all of this chapter.
C2. Migrate a JavaScript module to strict TypeScript
Take chapter 15's C1 API client (or any 300-line JavaScript module of yours) and migrate it to TypeScript in steps: (1) rename to .ts with allowJs/checkJs and JSDoc types first, (2) turn on strict, (3) add noUncheckedIndexedAccess and exactOptionalPropertyTypes, (4) remove every any and cast, replacing them with unknown and validation. Record each step's errors (count and kinds) and the real bugs they revealed.
Combines: refactoring discipline and tests (Vol 1 ch 02); error handling (ch 02); this volume's JavaScript semantics (ch 15) and all of this chapter.
C3. A type-safe event and analytics layer
Design a typed analytics module: an EventMap interface mapping event names (template-literal style 'menu:viewed', 'cart:item_added', 'checkout:failed') to their payload types; a track<E extends keyof EventMap>(name: E, payload: EventMap[E]) function that batches events, adds context (session ID, app version from __APP_VERSION__, page), respects a consent flag, sends with navigator.sendBeacon on page hide, and never throws. Add a Zod schema per event for validation in development builds only, and a compile-time test that every event in the map has a schema.
Combines: batching and queues (Vol 1 ch 03); reliability (ch 08's graceful shutdown ideas); network APIs (ch 09); this volume's storage and lifecycle events (ch 12), privacy and security (ch 12, 13), JavaScript (ch 15) and this chapter's mapped types, template literals and declaration merging.
What the chapter leaves out
tsconfig for real projects: project references and module resolution
Large codebases split TypeScript into project references (composite: true, tsc -b) so packages build incrementally and in dependency order (chapter 30's monorepos). Module resolution settings must match the runtime and bundler: "module": "nodenext" for Node packages (respecting package.json exports and requiring file extensions in relative ESM imports), "moduleResolution": "bundler" for apps built by Vite or webpack. isolatedModules/verbatimModuleSyntax keep code compatible with single-file transpilers (esbuild, SWC, Node's type stripping) by forcing import type for type-only imports. Many "works in the IDE but not in the build" problems are mismatched resolution settings.
Type-checking speed and the editor experience
tsc type-checks the whole program, which gets slow in big repos; most build tools (Vite, esbuild, SWC, Babel) only strip types and don't check them, so the check must run separately (tsc --noEmit in CI and in the editor). Speed tips: skipLibCheck, avoiding huge unions and deeply recursive types (T8), --incremental, project references, and tsc --extendedDiagnostics/--generateTrace to find slow types. Microsoft's native TypeScript compiler port (written in Go, previewed as TypeScript 7) promises roughly 10× faster checking, which changes these trade-offs; check its status before planning around slowness.
Linting with type information
ESLint with typescript-eslint's type-aware rules catches bug classes the compiler doesn't: floating promises and misused promises (chapter 15's T7), unsafe any flows (no-unsafe-assignment, no-unsafe-member-access), unnecessary conditions (no-unnecessary-condition: checks that can never be true given the types), exhaustive switches on unions (switch-exhaustiveness-check), and restricted template expressions. Combined with strict, they're the closest TypeScript gets to Java's compile-time strictness plus static analysis (Error Prone, SpotBugs).
Types for the DOM and frameworks
lib.dom.d.ts types the browser APIs, with some sharp edges: document.querySelector('#x') returns Element | null (use the generic form querySelector<HTMLInputElement>('#x') or check with instanceof), event targets are EventTarget | null (narrow e.currentTarget), and APIs newer than your lib setting appear missing. Framework typing patterns (typed props and children in React, typed forms and DI in Angular, typed stores) live in chapters 22–25, but they all rely on this chapter's generics, unions and inference.
When not to use TypeScript features
Some features cost more than they give in application code: namespaces (use modules), enums (T1), decorators with metadata outside frameworks that need them, abstract class hierarchies (prefer unions and functions), and complex type-level programming (T8). Also avoid "type theatre": types that look precise but aren't enforced at run time (an API response typed as Order without validation: T10). The goal is fewer bugs with less ceremony, not maximal type cleverness.
Senior exercises
S1. Review a pull request full of casts
A PR adds a "kitchen dashboard" with: const data = (await res.json()) as Dashboard, const el = document.getElementById('chart')!, props.items as any as Order[], catch (e: any) { toast(e.message) }, an enum OrderStatus { Placed, Paid } compared with numbers from the API, and // @ts-ignore above a call to a chart library. Write the review, ranked by severity, with the fix for each.
S2. Set TypeScript standards for the frontend
Write the team's TypeScript standard: compiler options, lint rules, how types are generated from the backend, rules for any/casts/non-null assertions, enums vs unions, branded IDs and money, where runtime validation is mandatory, and how type-level code is tested. For each, the reason and the enforcement.
S3. Plan a TypeScript migration for a large JavaScript codebase
TiffinBox's partner portal is 120,000 lines of JavaScript with React, written over five years. Plan its migration to TypeScript: order of work, configuration stages, how to keep shipping features meanwhile, how to measure progress, and what not to do.
S4. Decide how to share types between the Java backend and the TypeScript frontend
Compare: (a) generating TypeScript from the Spring backend's OpenAPI spec; (b) a schema-first approach (OpenAPI or JSON Schema written by hand, generating both Java and TypeScript); (c) protobuf/gRPC (with gRPC-Web or Connect for the browser); (d) GraphQL with codegen. Evaluate on: source of truth, versioning and breaking-change detection, runtime validation, developer workflow, and fit for TiffinBox. Recommend one.
S5. Explain structural typing and erasure to Java engineers
Write a one-page explainer for Java engineers starting on the TypeScript frontend: the five biggest differences from Java's type system (structural vs nominal, erasure and no runtime types, unions and narrowing instead of overloading and inheritance, null/undefined and optional properties, unsoundness and casts), each with a 3-line code example and the habit to adopt.