Homework

Homework — illegal states, unrepresentable

Homework — illegal states, unrepresentable.

  1. Describe Apod. Create src/types.ts with ApodImage, ApodVideo and the Apod union. Try to reach pic.hdurl without a check — the compiler rejects it; add if (pic.media_type === 'image') — it unlocks.
  2. Fix lesson 15's errors. Back in detail.ts: change pic.hdurl to pic.media_type === 'image' ? pic.hdurl : undefined (or narrow it) and guard pic.copyright. npm run typecheck — clean.
  3. Literal union. Define Rating. Try const r: Rating = 47 — error. const r: Rating = 5 — ok.
  4. LoadStatus. Define the LoadStatus union and AppState. Prove you can't construct "loading AND error": try status = { state: 'loading', message: 'x' } — error (loading has no message).
  5. Reflect on the principle. Where else in the app could an "illegal state" be made unrepresentable? (E.g. SortKey, Theme, routes.)

Required tests:

  • Narrowing test: hdurl is reachable only after the media_type check.
  • Unrepresentable test: { state: 'loading', error: ... } doesn't compile.

To submit: screenshots: (1) the hdurl error without a check and ✓ with one, (2) the Rating = 47 error, (3) the impossible "loading + error" state.

Next. Types describe what you expect. But in lesson 17 we'll see the hole: response.json() returns any — types don't check what you actually got from a real server. We'll learn type guards (value is Apod), so untrusted data at the network boundary becomes a trusted type.