Complete worked example
typescript
type ResponseLike = { ok: boolean; json(): Promise<unknown> };
async function load<T>(request: () => Promise<ResponseLike>, decode: (raw: unknown) => T | undefined): Promise<T> {
const response = await request();
if(!response.ok) throw new Error("HTTP failure");
const value = decode(await response.json());
if(value === undefined) throw new Error("Invalid payload");
return value;
}- Reasoning
- The decoder, not a caller assertion, justifies the helper’s successful generic output.