All writing

TypeScript and API design

Designing Explicit Outcomes for TypeScript API Clients

TypeScript API clients become more reliable when they model transport, HTTP, parsing, and domain outcomes separately instead of collapsing every failure into an exception.

Mubashir Hussain11 min read

An API client is often introduced as a convenience: give it a URL, ask for JSON, and return a typed object. That description is attractive because it keeps the first call site small. It also hides the information that matters most when a system has to make a decision after something goes wrong. A timeout, a rejected request, a valid 409 response, malformed JSON, and a business rule denial are not interchangeable. They call for different user messages, retry behavior, telemetry, and state changes.

TypeScript is useful here, but only if the client treats types as a description of observed outcomes rather than a promise made before the network is involved. A type assertion can make a response look complete even when a provider changed a field, a proxy returned an HTML error page, or an operation completed before the connection was lost. A durable client keeps those cases visible until the owning workflow deliberately resolves them.

This is especially important in products that coordinate several vendors. The Custom Name Domain portfolio project, for example, describes registrar, billing, DNS, and mail-provider operations moving through explicit provisioning stages. In that setting, a generic “request failed” result cannot tell a later stage whether it is safe to retry, whether a provider has already acted, or whether a human should investigate. The client contract needs to carry that distinction forward.

Start with the decision the caller must make

The first design question is not which HTTP library to use. It is what the caller needs to decide next. A payment update screen might need to show a correctable validation message. A provisioning worker might need to schedule a retry. A reconciliation task might need to stop because the remote side could have accepted the command even though the local process never received a response. Those are distinct decisions, so they deserve distinct outcomes.

Writing down these decisions prevents a common anti-pattern: returning a broad response type on success and throwing an unstructured error for everything else. That pattern turns the client into a source of guesses. Each caller starts inspecting strings, status codes, or provider-specific shapes independently. The result is inconsistent behavior and a migration problem whenever the provider evolves.

Instead, define a small vocabulary that matches the workflow. A read operation might have outcomes such as available, not-found, invalid-response, unavailable, and forbidden. A mutation might add accepted, rejected, conflict, uncertain, and rate-limited. The vocabulary should be intentionally smaller than the provider's full surface, but it should not erase a difference that changes the next action.

This is a boundary decision, not a claim that every endpoint has identical semantics. A client for a search endpoint can often safely retry a transient unavailable result. A client for a charge, domain purchase, or mailbox-creation endpoint cannot make that assumption merely because it used the same transport. The result model must preserve enough context for the workflow owner to apply the correct policy.

Model layers rather than one generic failure

A useful client separates at least four layers. Transport covers whether the process received a response at all. HTTP covers the response status and headers. Representation covers whether the body can be consumed and understood in the expected format. Domain covers the provider's documented business outcome. The layers happen in sequence, but they should not be collapsed into a single boolean.

For example, a network interruption before any response arrives is a transport outcome. A received 429 response is an HTTP outcome with retry guidance that may be expressed in headers or documented policy. A 200 response whose JSON body cannot be interpreted as the expected resource is a representation outcome. A well-formed 409 response saying that a resource already exists is a domain outcome. Treating all four as exceptions makes a critical state transition invisible.

A discriminated union is a natural way to encode this in TypeScript. The discriminant should express the action a caller can take, not a vague category such as error. Names like unavailable, rejected, invalid-response, conflict, and accepted read more clearly at the call site. TypeScript narrowing then requires a branch to establish which fields are safe to use. That is valuable because a retry delay does not belong on every failure, and a provider problem detail does not establish that an object was created.

The type should retain narrow evidence where it is safe and useful: a stable provider error code, a normalized status, a retry-after value that passed validation, or an opaque operation identifier. It should avoid turning the entire raw response into a universal error object. Raw bodies can be large, sensitive, unstable, and tempting for unrelated callers to depend on. Keep detailed diagnostics close to controlled logs or an authenticated operator view; return only the normalized facts the workflow needs.

Make uncertainty a first-class result

Many client libraries teach teams to catch an exception and retry. That is reasonable for a read that clearly did not leave the process. It becomes dangerous after a mutation has crossed a network boundary. A connection can fail after the remote service accepted the request but before its response reached the caller. From the local process, that is not the same as a confirmed rejection.

An explicit uncertain outcome changes the system's behavior for the better. It can cause a worker to pause the next transition, retain an idempotency key, and query a provider-specific status endpoint. It can show an operator that the correct task is reconciliation rather than repetition. It also prevents an optimistic UI from reporting a failure when the account may already have changed.

Idempotency keys support this design, but they do not remove the need to model uncertainty. Their value depends on the provider's documented scope, retention period, and response behavior. The client should generate or accept a stable key at the workflow boundary, attach it only where the provider supports it, and preserve it alongside the local command. A retry can then repeat the same intent rather than create a fresh request that looks identical to a person but is different to the provider.

The portfolio work on Custom Name Domain describes webhook-aware subscription state and staged provisioning. Those are examples of the kind of system where a later event or status read may be stronger evidence than a missing response. The engineering principle is broader: after an ambiguous mutation, reconcile authoritative state before advancing or resubmitting. A result type makes that rule visible to every caller.

Normalize problem details without pretending they are universal

HTTP status codes communicate useful general semantics, but a status alone rarely gives an application enough information to recover. RFC 9457 defines a machine-readable problem-details format for HTTP APIs, including fields such as a problem type, title, status, detail, and instance. A client can use a documented problem type as one input to its outcome mapping while still treating the response as untrusted data.

The normalization step should validate the response before using it. Check the content type when the provider documents one, bound the amount of body read, parse JSON defensively, and accept only the fields the client understands. A provider may return a proxy error, a gateway page, a different version of a problem document, or an unexpected extension member. None of those should become an unchecked cast.

Do not invent domain meaning from a title string. A human-readable title is useful for an operator or UI, but it is not a stable command language. Prefer a provider-documented type URI or code, then map known cases into the client's vocabulary. Unknown problem types should remain visible as an unrecognized rejection or invalid response, depending on what the provider guarantees. That choice is safer than silently treating unfamiliar denial as retryable.

This approach also keeps user-facing messages honest. The UI can say that an operation needs attention without exposing a provider payload. An authenticated operator surface can show a sanitized reference and the normalized reason. The workflow can preserve the full consequence: no retry for a confirmed validation rejection, delayed retry for a documented rate limit, and reconciliation for an ambiguous mutation.

Parse external data at one boundary

A TypeScript interface does not validate JSON received over the network. It describes values after the program has established that they meet the contract. The API boundary is where that establishment must happen. Parse and validate external data once, then expose a domain-shaped result to the rest of the application.

The boundary parser should be strict about fields that drive security or state transitions and intentionally tolerant about additive data that the application does not consume. For a resource identifier, status enum, amount, timestamp, or pagination cursor, validate the exact representation and range needed by the workflow. For unknown decorative fields, ignore them unless the product truly depends on them. This balance makes a client resilient to compatible additions without treating malformed critical data as valid.

Version changes deserve the same discipline. Avoid spreading provider response types through application components and job handlers. A provider adapter should translate its current schema into a local contract. When the provider adds a field, the adapter can ignore it. When a provider changes a required field or semantic, the adapter is the deliberate point of review. Without that seam, a small external change creates a broad, hard-to-audit migration.

The Elite Tech SaaS portfolio project describes provider wrappers coordinating external API operations, persistence, queues, and React forms. That architecture illustrates why the wrapper should own normalization instead of merely forwarding JSON. A form needs a safe actionable outcome; a queue needs retry or reconciliation guidance; persistence needs stable identifiers and state. Each consumer benefits when the adapter has already distinguished valid data from an unverified provider response.

Keep retry policy outside the parser

Parsing a response and deciding when to retry are related but separate responsibilities. The parser can establish that a response is a documented rate limit and safely extract a bounded retry delay. The workflow owns whether waiting is appropriate, how many attempts are acceptable, and when a person must intervene. Combining those decisions inside a generic fetch helper makes policy invisible and encourages reuse in the wrong context.

A useful retry policy considers operation kind, idempotency support, elapsed time, attempt count, and evidence of remote state. Reads may have a bounded backoff policy. Confirmed rate limits may have a documented delay. Mutations with an idempotency key may retry the identical intent under a defined window. Mutations without a safe replay mechanism should move to uncertainty and reconciliation rather than automatically loop.

This separation also makes testing more meaningful. A client test can cover mappings from representative transport, HTTP, representation, and domain inputs to normalized outcomes. A workflow test can cover how it reacts to those outcomes: retry, display a message, hold a state transition, or begin reconciliation. The tests are smaller because they do not need to mock every detail of a network stack at every call site.

The Fetch standard is a reminder that fetching involves more than a URL and a body. Redirect behavior, response properties, headers, credentials, and cross-origin rules all shape what a client can observe. A production wrapper should set its own explicit constraints, such as time bounds and acceptable redirects, rather than assuming a convenient default applies equally to every provider operation.

Let state machines consume outcomes deliberately

The highest value of an explicit client contract appears after the request finishes. Rather than allowing a catch block to write a generic failed state, a workflow can map each result to a permitted transition. Accepted may advance a command. Rejected may return the entity to an editable state. Conflict may require a fresh read. Unavailable may schedule a bounded retry. Uncertain may freeze the next action pending reconciliation.

That mapping is also an audit tool. When a new provider behavior appears, reviewers can ask a concrete question: which transition should this normalized outcome allow? If the answer is unclear, the safe default is to keep the workflow from advancing. This is much easier to reason about than hidden exception handling distributed across a background job, an API route, and a UI callback.

The goal is not to eliminate all failures or encode every vendor quirk in a union. It is to preserve the distinctions that affect customer data, external side effects, and operational decisions. A TypeScript API client becomes trustworthy when it reports what it knows, marks what it cannot know, and leaves the next decision to the workflow that owns the consequences.

Adopt the pattern incrementally

Teams do not need to replace every HTTP call at once. Begin with operations that change money, access, provisioning, or durable status. List the outcomes already observed in incidents and support work. Decide which are confirmed, retryable, correctable, or uncertain. Build one adapter with a compact result union, validation at its boundary, and tests for the mapping.

Then update one workflow to consume that union through explicit transitions. Measure success by clearer recovery behavior, not by fewer type declarations. The strongest result is a system that can explain why it paused, why it retried, and what evidence it needs before it acts again.

Primary sources

  1. 1.Narrowing — TypeScript
  2. 2.Problem Details for HTTP APIs — IETF
  3. 3.Fetch Standard — WHATWG

Portfolio evidence

Related writing