Homework
Homework — a trusted boundary
Homework — a trusted boundary.
- Type guard. In
src/lib/api.tswriteisApod(value: unknown): value is Apodandrequest(): Promise<unknown>. HavefetchPicturesreturndata.filter(isApod). - Prove the hole. Temporarily change
request's return toPromise<any>and assign directlyconst pics: Apod[] = data. The compiler is silent. Restoreunknown— now it demands the guard. That's the difference between "I expect" and "I checked". - Break the API. Simulate a changed response (e.g. an object with no
url). With the guard it's simply filtered out; without it, the gallery would try to renderundefinedand crash. - Readonly. In
state.ts, havegetState()returnReadonly<AppState>. TrygetState().pictures = []— error. Change it through an action — works. - catch unknown. In
errors.ts,toMessage(error: unknown). Tryerror.messagewithoutinstanceof— error ('error' is of type 'unknown'). Addinstanceof— ok.
Required tests:
- Boundary test: without the guard,
unknownwon't compile asApod[]; with it, it's trusted. - Readonly test: assigning to a
getState()field doesn't compile.
To submit: screenshots: (1) the any vs unknown difference (the hole), (2) the Readonly assignment error, (3) catch unknown requiring instanceof.
Next. We have solid boundaries and typed state. But so far we've turned on only basic strictness. In lesson 18 we'll see what the strict flags buy:
noUncheckedIndexedAccess(an array index can beundefined),exactOptionalPropertyTypes, andassertNever— an exhaustiveness guarantee that forces you to handle every union variant.