Basic Usage

Generated clients are the main way most apps call a Typeweaver API. The flow stays consistent: create a resource client, send an operation command, handle the typed response union, and catch infrastructure failures separately.

The basic flow

import { GetTodoRequestCommand, TodoClient } from "./api/generated";

const client = new TodoClient({
  baseUrl: "/api",
});

const response = await client.send(
  new GetTodoRequestCommand({
    param: {
      todoId: "todo_123",
    },
  })
);

if (response.type === "GetTodoSuccess") {
  console.log(response.body.title);
}

That is the standard pattern:

  1. create the generated resource client
  2. create the generated request command
  3. call client.send(...)
  4. branch on response.type

Creating the client

The generated resource client, such as TodoClient, groups operations for that resource.

const client = new TodoClient({
  baseUrl: "https://api.example.com",
  timeoutMs: 5_000,
});

baseUrl is required. fetchFn and timeoutMs are optional.

If your runtime already provides globalThis.fetch, you usually only need baseUrl. Pass fetchFn when you need a custom transport, such as tests, mocked fetch behavior, or a runtime without a global fetch.

In most apps, the client instance is created once and reused.

Creating the command

Each operation gets its own request command class.

const command = new GetTodoRequestCommand({
  param: {
    todoId: "todo_123",
  },
});

If the operation requires headers, query values, or a body, you pass those here too.

Sending the request

Generated clients use the same call shape everywhere:

const response = await client.send(command);

This keeps usage consistent whether you are calling GetTodo, CreateTodo, or UpdateTodo.

This page focuses on using generated clients in app code. For what the clients plugin generates in the first place, see Clients.

Reading the typed response

The returned value is a generated response union.

switch (response.type) {
  case "GetTodoSuccess":
    return response.body;
  case "TodoNotFoundError":
    return null;
}

Use response.type as the normal branching key.

What errors are not in the response union

Declared API outcomes come back as normal responses. Infrastructure-level failures are thrown instead, such as:

  • NetworkError
  • ResponseParseError
  • PathParameterError
  • UnknownResponseError

Use catch for those. Use response.type for documented API outcomes.

Was this page helpful?