TypeScript Lab Examples
Every demo is a single self-contained file with a purpose statement, didactic
comments, and expected output. .ts demos run directly with
node <file> (Node ≥ 22.18 has type stripping built in) or
npx tsx <file> for full language support. .html demos
are self-contained — open them directly in a browser. The Source column
opens the file in the code viewer; the Preview column runs it.
Phase 1 — Foundations: erasure and strict mode
| # | Description | Source | Preview |
| 01 | Type erasure — compile one file and see that no type syntax survives into the emitted JavaScript | 01_type_erasure.ts | — |
| 02 | Strict mode catches the classic undefined-property bug at compile time — uncomment lines to watch it fail | 02_strict_catches_bugs.ts | — |
Phase 2 — The type system: unions, state machines, generics
Phase 3 — Advanced type programming
| # | Description | Source | Preview |
| 06 | Mapped and conditional types — patch objects, string-field filters and Unwrap computed from one source type | 06_mapped_and_conditional.ts | — |
| 07 | Template literal types — event names whose cross product the compiler computes; typos become compile errors | 07_template_literal_types.ts | — |
Phase 4 — Production: errors and parsing
| # | Description | Source | Preview |
| 08 | Result error handling — failure as a typed return value; the compiler refuses to let a caller forget the error branch | 08_result_error_handling.ts | — |
| 09 | A 40-line Zod core — "parse, don't validate": composable parsers that return the checked value, not just a verdict | 09_minimal_validator.ts | — |
Phase 5 — Practice: classes, DOM, and state stores
| # | Description | Source | Preview |
| 10 | Bank account — private fields and Result returns make an overdrawn account impossible to construct | 10_bank_account.ts | — |
| 11 | Greeter widget — typed DOM access: the null guard the checker demands, shown next to the JS it emits. Runs in the browser | 11_greeter_widget.html | preview |
| 12 | Todo store — a discriminated-union action set driving a unidirectional store, with the reducer shown both typed and emitted. Runs in the browser | 12_todo_store.html | preview |
How to study it
- Read the header comment first. Every demo states its purpose, the run command, and what you should learn from it — then run it and check the output against the expectations in the comments.
- Break it on purpose. Each demo has commented-out lines that fail the checker (demos 02, 05, 07) or show a guard. Uncomment them and read the error — the diagnostics teach more than the happy path does.
- Compare source and emit. Run
npx tsc 01_type_erasure.ts and diff the output against the original; the erased lines are exactly the type system's design-time half.
- Rebuild from memory. After studying a demo, delete the file and reproduce it. If you cannot, the missing piece names the lesson to re-read — each demo links back to one.