Homework
Homework — illegal states, unrepresentable
Homework — illegal states, unrepresentable.
- Describe
Apod. Createsrc/types.tswithApodImage,ApodVideoand theApodunion. Try to reachpic.hdurlwithout a check — the compiler rejects it; addif (pic.media_type === 'image')— it unlocks. - Fix lesson 15's errors. Back in
detail.ts: changepic.hdurltopic.media_type === 'image' ? pic.hdurl : undefined(or narrow it) and guardpic.copyright.npm run typecheck— clean. - Literal union. Define
Rating. Tryconst r: Rating = 47— error.const r: Rating = 5— ok. - LoadStatus. Define the
LoadStatusunion andAppState. Prove you can't construct "loading AND error": trystatus = { state: 'loading', message: 'x' }— error (loadinghas nomessage). - 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:
hdurlis reachable only after themedia_typecheck. - 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()returnsany— 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.