Typed API client

The programs here call the API through a stand-in answer of one user, so each pair of request and print can be read without a server; the shapes and the helpers are the lesson. The two helpers need that server to answer, so their lines below are the answers it gives, not lines a command-line run can print.

Type the responses

A typed client starts with response shapes written as plain interfaces. Every helper then promises exactly that shape, so screens get completion instead of guessing field names.

Keep shapes narrow and close to what the screen needs. Small response types expose server drift early, while giant shared types hide it until runtime. The program builds one value of each interface and prints a field of it.

interface User { id: string; name: string; } interface ApiError { status: number; message: string; } const user: User = { id: "7", name: "Ada" }; const err: ApiError = { status: 404, message: "User not found" }; console.log(user.name, err.status);

Ada 404

GET helper

One async GET helper can serve every read endpoint. It takes a path, checks the status, and returns parsed JSON cast to the expected generic type.

Call sites stay tiny because the helper owns headers, status checks, and parsing. Reading data looks like calling a function, not juggling low level response details. The program asks for one user through the helper and prints the id and the name.

interface User { id: string; name: string; } async function apiGet<T>(path: string): Promise<T> { const res = await fetch(path); if (!res.ok) { throw new Error("GET failed: " + res.status); } return res.json() as Promise<T>; } async function main(): Promise<void> { const user = await apiGet<User>("/users/7"); console.log(user.id, user.name); } main();

7 Ada

POST helper

Writes need the same care with one extra input: the request body. A POST helper stringifies the payload, sets the JSON header, and returns the created resource type.

Mirroring GET keeps the client predictable. Two helpers with the same error style cover most small apps without a class hierarchy or extra runtime. The program posts one user and prints the created record.

interface User { id: string; name: string; } async function apiPost<T>(path: string, body: unknown): Promise<T> { const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); if (!res.ok) { throw new Error("POST failed: " + res.status); } return res.json() as Promise<T>; } async function main(): Promise<void> { const user = await apiPost<User>("/users", { name: "Bob" }); console.log(user.id, user.name); } main();

8 Bob

Throw typed errors

Network code fails for honest reasons: lost connection, missing record, or invalid input. Throw shaped errors with status plus message so handlers can branch without parsing text.

Catch at the screen level where a fallback exists, not inside every helper. Helpers report precisely, screens decide between retry, redirect, and a calm message. The program throws one shaped error, catches it and prints the status with the message.

interface ApiError { status: number; message: string; } function toApiError(status: number, message: string): ApiError { return { status, message }; } try { throw toApiError(404, "User not found"); } catch (err: unknown) { const apiError = err as ApiError; console.log(apiError.status, apiError.message); }

404 User not found

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why write response shapes as interfaces?

    Answer

    They give the helpers a precise return type and catch server drift early

    The interface is a promise about the answer, and the compiler checks every field the screens read.

  2. What does one apiGet<T> helper own?

    Answer

    The request, the status check, the parse, and the return type

    One helper keeps every read endpoint on the same path, and call sites stay one line long.

  3. Where should an API error be caught?

    Answer

    At the screen, where a fallback exists

    Helpers report precisely and the screen decides between a retry, a redirect and a calm message.

  4. Why does apiPost take body: unknown?

    Answer

    Any value may be posted, and JSON.stringify accepts any of them

    The helper only turns the value into JSON, so it needs no knowledge of the payload shape.

  5. What does this program print? interface User { id: string; name: string; } const user: User = { id: "7", name: "Ada" }; console.log(user.name, user.id);

    Answer

    Ada 7

    The fields are read in the order of the log call, name first and id second.

  6. What does this program print? function toApiError(status: number, message: string): { status: number; message: string } { return { status, message }; } const err = toApiError(404, "User not found"); console.log(err.status, err.message);

    Answer

    404 User not found

    The helper builds the object from its arguments, and the two fields print in order.

  7. What does this program print? async function apiGet(path: string): Promise<{ ok: boolean }> { return { ok: path === "/users/7" }; } async function main(): Promise<void> { const first = await apiGet("/users/7"); const second = await apiGet("/users/8"); console.log(first.ok, second.ok); } main();

    Answer

    true false

    Only the first path matches the one the helper accepts, so the two flags differ.

  8. What does this program print? interface ApiError { status: number; message: string; } try { throw { status: 500, message: "server" } as ApiError; } catch (err: unknown) { console.log((err as ApiError).message); }

    Answer

    server

    The thrown value carries the message, and the catch reads it through the interface.

  9. What does the compiler say about this program? interface User { id: string; name: string; } const user: User = { id: 7, name: "Ada" }; console.log(user.name);

    Answer

    error TS2322: Type 'number' is not assignable to type 'string'.

    The interface declares the id as text, and the number in the object does not fit it.

  10. What does the compiler say about this program? interface User { id: string; name: string; } const user: User = { id: "7" }; console.log(user.name);

    Answer

    error TS2741: Property 'name' is missing in type '{ id: string; }' but required in type 'User'.

    The interface requires both fields, and the object literal leaves one out.

Article author: Arthur Isaev