Skip to content

Typed client

This guide gives a frontend or another service a client with typed paths, bodies and errors.

  • @tetsujs/client, for your own frontends in TypeScript. Its types are the ones your handlers see, taken from the compiler.
  • The OpenAPI document, for other languages, other teams and public APIs.

A frontend does not import the server’s code. It imports a contract: a .d.ts file of plain types that tetsu-client contract generates from the application. Add a script to the server:

package.json
"contract": "tetsu-client contract src/app.ts --out ../web/src/api.contract.d.ts"

The frontend creates its client with it:

import { createClient } from "@tetsujs/client";
import type { Api } from "./api.contract";
export const
const api: Client<Api, ClientTypes>
api
= createClient<Api>({
baseUrl?: string | URL | undefined

Where the application is, put before every path — https://api.example.com or https://example.com/api. A trailing slash is dropped. Empty by default: the paths stay relative, for a fetch that resolves them itself.

baseUrl
: "https://api.example.com" });

Commit the contract, so every API change shows up as a diff, and check it in CI:

Terminal window
bunx tetsu-client contract src/app.ts --out ../web/src/api.contract.d.ts --check

In a monorepo, run the same command with --watch while you work, and the frontend sees a new route as soon as it is saved. Importing typeof app into the frontend also works, but it makes the frontend compile the server’s code with Bun’s types; keep that for tests and Bun projects.

@tetsujs/client/tanstack turns the client into TanStack Query options:

import { useQuery } from "@tanstack/react-query";
import { queryUtils } from "@tetsujs/client/tanstack";
import { api } from "./api";
const
const q: QueryUtils<Api, ClientTypes>
q
= queryUtils(api);
const
const user: UseQueryResult<{
id: number;
name: string;
}, ClientError<Failure<404, {
status: 404;
message: string;
error: "USER_NOT_FOUND";
}>> | ClientError<Failure<400 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451, ErrorBody>> | ClientError<Failure<500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511, ErrorBody | undefined>>>
user
= useQuery(
const q: QueryUtils<Api, ClientTypes>
q
.get("/users/:id").queryOptions({
params: {
id: number;
}
params
: {
id: number
id
} }));
if (
const user: UseQueryResult<{
id: number;
name: string;
}, ClientError<Failure<404, {
status: 404;
message: string;
error: "USER_NOT_FOUND";
}>> | ClientError<Failure<400 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451, ErrorBody>> | ClientError<Failure<500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511, ErrorBody | undefined>>>
user
.
error: ClientError<Failure<404, {
status: 404;
message: string;
error: "USER_NOT_FOUND";
}>> | ClientError<Failure<400 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451, ErrorBody>> | ClientError<Failure<500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511, ErrorBody | undefined>> | null

The error the refetch failed with.

null, since the query isn't in the error state.

The error the first fetch failed with.

error
?.
status: 404 | 400 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511 | undefined
status
=== 404) {
console.log(
const user: UseQueryResult<{
id: number;
name: string;
}, ClientError<Failure<404, {
status: 404;
message: string;
error: "USER_NOT_FOUND";
}>> | ClientError<Failure<400 | 401 | 402 | 403 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451, ErrorBody>> | ClientError<Failure<500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511, ErrorBody | undefined>>>
user
.
error: ClientError<Failure<404, {
status: 404;
message: string;
error: "USER_NOT_FOUND";
}>>

The error the refetch failed with.

null, since the query isn't in the error state.

The error the first fetch failed with.

error
.
body: {
status: 404;
message: string;
error: "USER_NOT_FOUND";
}
body
.error);
error: "USER_NOT_FOUND"
}

The same options work with Svelte, Vue and Solid; those adapters take a function that returns them, such as createQuery(() => q.get(…).queryOptions(…)). A mutation is useMutation(q.post("/users").mutationOptions()), and invalidateQueries({ queryKey: q.get("/users").key() }) refreshes every query of a route.

Two things are worth setting once. Send authorization from the client, not from each call: a call’s headers are part of its query key, and would end up in the cache. And retry only server errors and network failures, since TanStack Query retries everything three times by default in the browser, and a 404 would show only after them:

import { QueryClient } from "@tanstack/react-query";
import { ClientError, createClient } from "@tetsujs/client";
export const
const api: Client<Api, {
headers: "authorization";
}>
api
= createClient<Api, {
headers: "authorization"
headers
: "authorization" }>({
headers?: HeadersInit | (() => HeadersInput | Promise<HeadersInput>) | undefined

Headers sent with every request, or a function that returns them — asked again for each request, so a token read from a store is always the current one. A header a call sets wins over these.

headers
: () => ({
authorization: string
authorization
: `Bearer ${currentToken()}` }),
});
export const
const retry: (count: number, error: Error) => boolean
retry
= (
count: number
count
: number,
error: Error
error
: Error) =>
!(
error: Error
error
instanceof ClientError &&
error: ClientError<any>
error
.
status: any
status
< 500) &&
count: number
count
< 3;
export const
const queryClient: QueryClient
queryClient
= new QueryClient({
defaultOptions?: DefaultOptions<Error> | undefined

Default options for all queries and mutations created through this client.

defaultOptions
: {
queries?: OmitKeyof<QueryObserverOptions<unknown, Error, unknown, unknown, readonly unknown[], never>, "suspense" | "queryKey", "strictly"> | undefined

Default options applied to every query, unless overridden per-query.

queries
: {
retry?: RetryValue<Error> | undefined

If false, failed queries will not retry by default. If true, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.

Defaults to 3 on the client and 0 on the server.

retry
} },
});

A query of a stream is TanStack Query’s streamedQuery, fed by the call’s events. The options of queryUtils read one body and are done, so on a stream they fail the query with a TypeError rather than leave the connection open. TanStack Query retries that error like any other, so it shows after the retries.

import {
experimental_streamedQuery as streamedQuery,
queryOptions,
useQuery,
} from "@tanstack/react-query";
import { ClientError } from "@tetsujs/client";
import { api } from "./api";
const
const reply: (input: string) => OmitKeyof<UseQueryOptions<string, Error, string, string[]>, "queryFn"> & {
queryFn?: QueryFunction<string, string[], never> | undefined;
} & QueryKeyWithDataTag<string[], string, Error>
reply
= (
input: string
input
: string) =>
queryOptions({
queryKey: string[]

The query key to use for this query.

The query key will be hashed into a stable hash. See Query Keys for more information.

The query will automatically update when this key changes (as long as enabled is not set to false).

queryKey
: ["reply",
input: string
input
],
queryFn?: QueryFunction<string, string[], never> | undefined

skipToken is not allowed as a value here — this overload is selected when no initialData is set. If you don't intend to run the query yet, set enabled: false — omitting queryFn alone still triggers a fetch that fails with "Missing queryFn" unless enabled is false or a default query function has been defined. A default query function only supplies queryFn; it doesn't defer the fetch on its own.

queryFn
: streamedQuery({
streamFn: (context: {
client: QueryClient;
queryKey: string[];
signal: AbortSignal;
meta: QueryMeta | undefined;
pageParam?: unknown;
direction?: unknown;
}) => AsyncIterable<string> | Promise<AsyncIterable<string>>

The function that returns an AsyncIterable to stream data from.

streamFn
: async function* ({
signal: AbortSignal
signal
}) {
const res = await api.post("/agents/:name/stream", {
params: {
readonly name: string | number;
}
params
: {
name: string | number
name
: "chat" },
body: {
input: string;
}
body
: {
input: string
input
},
init?: Omit<RequestInit, "body" | "headers" | "method"> | undefined

The rest of fetch's options — signal, credentials, cache.

init
: {
signal?: AbortSignal | null | undefined

An AbortSignal to set request's signal.

signal
},
});
if (!res.
ok: boolean
ok
) throw new ClientError(
const res: Undeclared<{
readonly 200: Raw<"text/event-stream", {
type: "delta";
delta: string;
} | {
type: "done";
}>;
}, ErrorBody>
res
);
for await (const
const event: ReceivedEvent<{
type: "delta";
delta: string;
} | {
type: "done";
}>
event
of
const res: Success<200, undefined> & {
readonly events: AsyncIterable<ReceivedEvent<{
type: "delta";
delta: string;
} | {
type: "done";
}>>;
}
res
.
events: AsyncIterable<ReceivedEvent<{
type: "delta";
delta: string;
} | {
type: "done";
}>>

The events of the stream, read as they are iterated. Leaving the loop closes the connection, and the call's signal aborts it; a stream that is never read stays open until the signal aborts it or response.body is cancelled. Read once.

events
) {
if (
const event: ReceivedEvent<{
type: "delta";
delta: string;
} | {
type: "done";
}>
event
.
data: {
type: "delta";
delta: string;
} | {
type: "done";
}
data
.
type: "delta" | "done"
type
=== "delta") yield
const event: ReceivedEvent<{
type: "delta";
delta: string;
} | {
type: "done";
}>
event
.
data: {
type: "delta";
delta: string;
}
data
.
delta: string
delta
;
}
},
reducer: (acc: string, chunk: string) => string

Reduces streamed chunks into the final data shape. Required whenever TData is not an array, since there is no default way to accumulate non-array chunks.

reducer
: (
text: string
text
,
delta: string
delta
) =>
text: string
text
+
delta: string
delta
,
initialValue: string

The value used while the first chunk is being fetched, and returned if the stream yields no values. Required together with a custom reducer.

initialValue
: "",
}),
staleTime?: StaleTimeFunction<string, Error, string, string[]> | undefined

The time in milliseconds after data is considered stale. If set to Infinity, the data will never be considered stale. If set to 'static', the data will never be considered stale. If set to a function, the function will be executed with the query to compute a staleTime.

@defaultValue ― 0

staleTime
: Number.
type POSITIVE_INFINITY: number

A value greater than the largest number that can be represented in JavaScript. JavaScript displays POSITIVE_INFINITY values as infinity.

POSITIVE_INFINITY
,
retry?: RetryValue<Error> | undefined

If false, failed queries will not retry by default. If true, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.

Defaults to 3 on the client and 0 on the server.

retry
: false,
});
const { data } = useQuery(
const reply: (input: string) => OmitKeyof<UseQueryOptions<string, Error, string, string[]>, "queryFn"> & {
queryFn?: QueryFunction<string, string[], never> | undefined;
} & QueryKeyWithDataTag<string[], string, Error>
reply
("Hello"));
const data: string | undefined

The query shows the text as it grows, and stays fetching until the stream ends. Its signal goes to the call, so a query that is cancelled or loses its last observer closes the stream. A stream that starts work on the server should not start it again by itself: staleTime keeps the query from refetching when the window regains focus or a component mounts, and retry: false from running the agent again after a failure. streamedQuery is still experimental in TanStack Query.

On the server, a component renders for a request whose cookies the client has to pass on itself. A client is cheap to create, so make one per request:

src/api.ts
import { createClient } from "@tetsujs/client";
import type { Api } from "./api.contract";
export function api(
cookie: string | undefined
cookie
?: string) {
return createClient<Api>({
baseUrl?: string | URL | undefined

Where the application is, put before every path — https://api.example.com or https://example.com/api. A trailing slash is dropped. Empty by default: the paths stay relative, for a fetch that resolves them itself.

baseUrl
: process.
env: NodeJS.ProcessEnv

The process.env property returns an object containing the user environment. See environ(7).

An example of this object looks like:

{
"TERM": "xterm-256color",
"SHELL": "/usr/local/bin/bash",
"USER": "maciej",
"PATH": "~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin",
"PWD": "/Users/maciej",
"EDITOR": "vim",
"SHLVL": "1",
"HOME": "/Users/maciej",
"LOGNAME": "maciej",
"_": "/usr/local/bin/node"
}

It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other Worker threads. In other words, the following example would not work:

Terminal window
node -e 'process.env.foo = "bar"' &#x26;&#x26; echo $foo

While the following will:

import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);

Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'

Use delete to delete a property from process.env.

import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined

On Windows operating systems, environment variables are case-insensitive.

import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1

Unless explicitly specified when creating a Worker instance, each Worker thread has its own copy of process.env, based on its parent thread's process.env, or whatever was specified as the env option to the Worker constructor. Changes to process.env will not be visible across Worker threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner unlike the main thread.

@since ― v0.1.27

env
.NEXT_PUBLIC_API_URL,
headers?: HeadersInit | (() => HeadersInput | Promise<HeadersInput>) | undefined

Headers sent with every request, or a function that returns them — asked again for each request, so a token read from a store is always the current one. A header a call sets wins over these.

headers
:
cookie: string | undefined
cookie
=== undefined ? undefined : {
cookie: string
cookie
},
});
}

A server component prefetches the query and hands the cache to the browser:

app/users/[id]/page.tsx
import { dehydrate, HydrationBoundary, QueryClient } from "@tanstack/react-query";
import { queryUtils } from "@tetsujs/client/tanstack";
import { cookies } from "next/headers";
import { api } from "./api";
import { User } from "./user";
export default async function Page({
params: Promise<{
id: string;
}>
params
}: {
params: Promise<{
id: string;
}>
params
: Promise<{
id: string
id
: string }> }) {
const
const id: number
id
= Number((await
params: Promise<{
id: string;
}>
params
).
id: string
id
);
const
const q: QueryUtils<Api, ClientTypes>
q
= queryUtils(api((await cookies()).toString()));
const
const queryClient: QueryClient
queryClient
= new QueryClient();
// A failure is left to the browser, which fetches again and shows it.
await
const queryClient: QueryClient
queryClient
.query(
const q: QueryUtils<Api, ClientTypes>
q
.
get: <Api, ClientTypes, "/users/:id">(this: QueryUtils<Api, ClientTypes>, path: "/users/:id") => Endpoint<{
readonly request: {
readonly params: {
id: number;
};
readonly headers?: Readonly<Record<string, HeaderValue>> | undefined;
};
readonly responses: {
readonly "2XX": {
id: number;
name: string;
};
};
}, ClientTypes, "GET", "/users/:id">
get
("/users/:id").queryOptions({
params: {
id: number;
}
params
: {
id: number
id
} })).catch(() => undefined);
return (
<HydrationBoundary
state: DehydratedState | null | undefined

The state to hydrate.

state
={dehydrate(
const queryClient: QueryClient
queryClient
)}>
<User
id: number
id
={
const id: number
id
} />
</HydrationBoundary>
);
}

User is a client component that calls useQuery with the same options, over queryUtils(api()): in the browser, the browser sends the cookies. Its query client comes from a provider in the root layout, with the retry above:

app/providers.tsx
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { type ReactNode, useState } from "react";
import { retry } from "./retry";
export function Providers({
children: ReactNode
children
}: {
children: ReactNode
children
: ReactNode }) {
const [
const queryClient: QueryClient
queryClient
] = useState(() => new QueryClient({
defaultOptions?: DefaultOptions<Error> | undefined

Default options for all queries and mutations created through this client.

defaultOptions
: {
queries?: OmitKeyof<QueryObserverOptions<unknown, Error, unknown, unknown, readonly unknown[], never>, "suspense" | "queryKey", "strictly"> | undefined

Default options applied to every query, unless overridden per-query.

queries
: {
retry?: RetryValue<Error> | undefined

If false, failed queries will not retry by default. If true, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.

Defaults to 3 on the client and 0 on the server.

retry
} } }));
return <QueryClientProvider
client: QueryClient

Required

The QueryClient instance to provide.

client
={
const queryClient: QueryClient
queryClient
}>{
children: ReactNode
children
}</QueryClientProvider>;
}

For an API on another origin, pass init: { credentials: "include" } to the client. In a monorepo on Bun, set "types": ["node"] in the Next.js tsconfig.json, or it picks up Bun’s types from the root.

A load function gets SvelteKit’s fetch, which carries the request’s cookies on the server. Pass it to the client:

src/lib/api.ts
import { createClient } from "@tetsujs/client";
import type { Api } from "./api.contract";
export function api(
fetch: typeof globalThis.fetch
fetch
= globalThis.fetch) {
return createClient<Api>({
baseUrl?: string | URL | undefined

Where the application is, put before every path — https://api.example.com or https://example.com/api. A trailing slash is dropped. Empty by default: the paths stay relative, for a fetch that resolves them itself.

baseUrl
: "https://api.example.com",
fetch?: Fetch | undefined

The fetch to send with. The global fetch by default.

fetch
});
}

While it renders, SvelteKit’s fetch hides the headers of a response unless a hook lets them through, and the client reads content-type. Without the hook, every load that calls the client fails with a 500:

src/hooks.server.ts
import type { Handle } from "@sveltejs/kit/hooks";
export const
const handle: Handle
handle
: Handle = ({
event: unknown
event
,
resolve: (event: unknown, options?: {
filterSerializedResponseHeaders?(name: string): boolean;
}) => Promise<Response>
resolve
}) =>
resolve: (event: unknown, options?: {
filterSerializedResponseHeaders?(name: string): boolean;
}) => Promise<Response>
resolve
(
event: unknown
event
, { filterSerializedResponseHeaders: (
name: string
name
) =>
name: string
name
=== "content-type" });

In SvelteKit 2, Handle comes from @sveltejs/kit. For an API on another origin, the server’s fetch asks for CORS headers as a browser does, so the application needs cors for the frontend’s origin.

With TanStack Query, the root layout creates the query client, with queries off on the server, where load functions prefetch instead, and the retry above: a load runs in the browser too, and waits for every retry.

src/routes/+layout.ts
import { QueryClient } from "@tanstack/svelte-query";
import { browser } from "$app/env";
import { retry } from "#lib/api.ts";
import type { LayoutLoad } from "./$types";
export const
const load: LayoutLoad
load
: LayoutLoad = () => ({
queryClient: QueryClient
queryClient
: new QueryClient({
defaultOptions?: DefaultOptions<Error> | undefined

Default options for all queries and mutations created through this client.

defaultOptions
: {
queries?: OmitKeyof<QueryObserverOptions<unknown, Error, unknown, unknown, readonly unknown[], never>, "suspense" | "queryKey", "strictly"> | undefined

Default options applied to every query, unless overridden per-query.

queries
: {
enabled?: QueryBooleanOption<unknown, Error, unknown, readonly unknown[]> | undefined

Set this to false or a function that returns false to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the refetch method returned from the useQuery instance. Accepts a boolean or function that returns a boolean.

@defaultValue ― true

enabled
: browser,
retry?: RetryValue<Error> | undefined

If false, failed queries will not retry by default. If true, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false.

Defaults to 3 on the client and 0 on the server.

retry
} } }),
});
src/routes/users/[id]/+page.ts
import { queryUtils } from "@tetsujs/client/tanstack";
import { api } from "#lib/api.ts";
import type { PageLoad } from "./$types";
export const
const load: PageLoad
load
: PageLoad = async ({
fetch: typeof fetch
fetch
,
params: {
id: string;
}
params
,
parent: () => Promise<{
queryClient: QueryClient;
}>
parent
}) => {
const {
const queryClient: QueryClient
queryClient
} = await
parent: () => Promise<{
queryClient: QueryClient;
}>
parent
();
const
const id: number
id
= Number(
params: {
id: string;
}
params
.
id: string
id
);
const
const q: QueryUtils<Api, ClientTypes>
q
= queryUtils(api(
fetch: typeof fetch
fetch
));
await
const queryClient: QueryClient
queryClient
.query(
const q: QueryUtils<Api, ClientTypes>
q
.
get: <Api, ClientTypes, "/users/:id">(this: QueryUtils<Api, ClientTypes>, path: "/users/:id") => Endpoint<any, ClientTypes, "GET", "/users/:id">
get
("/users/:id").queryOptions({
params: {
id: number;
}
params
: {
id: number
id
} })).catch(() => undefined);
return {
id: number
id
};
};

The page calls createQuery(() => q.get("/users/:id").queryOptions({ params: { id: data.id } })) over queryUtils(api()) and finds the user in the cache. Wrap the layout in QueryClientProvider with data.queryClient, as the Svelte Query docs show.

Nuxt, SolidStart and other frameworks follow the same idea: a client per request that passes its cookies on, and prefetching as TanStack Query’s guide for that framework describes.

@tetsujs/openapi serves the document at /openapi.json. openapi-typescript turns it into types:

Terminal window
bunx openapi-typescript http://localhost:3000/openapi.json -o src/openapi.d.ts

and openapi-fetch calls the API with them:

import createClient from "openapi-fetch";
import type { paths } from "./openapi";
const
const api: Client<paths, `${string}/${string}`>
api
= createClient<paths>({
baseUrl?: string | undefined

set the common root URL for all API requests

baseUrl
: "https://api.example.com" });
const {
const data: {
id: number;
name: string;
} | undefined
data
,
const error: Readable<ErrorResponse<{
200: Json<{
id: number;
name: string;
}>;
404: Json<components["schemas"]["UserNotFound"]>;
422: Json<components["schemas"]["ValidationFailed"]>;
500: Json<components["schemas"]["InternalServerError"]>;
}, `${string}/${string}`>> | undefined
error
} = await
const api: Client<paths, `${string}/${string}`>
api
.GET("/users/{id}", {
params: {
path: {
id: number;
};
}
params
: {
path: {
id: number;
}
path
: {
id: number
id
: 42 } } });
if (
const error: Readable<ErrorResponse<{
200: Json<{
id: number;
name: string;
}>;
404: Json<components["schemas"]["UserNotFound"]>;
422: Json<components["schemas"]["ValidationFailed"]>;
500: Json<components["schemas"]["InternalServerError"]>;
}, `${string}/${string}`>> | undefined
error
) {
console.log(
const error: Readable<ErrorResponse<{
200: Json<{
id: number;
name: string;
}>;
404: Json<components["schemas"]["UserNotFound"]>;
422: Json<components["schemas"]["ValidationFailed"]>;
500: Json<components["schemas"]["InternalServerError"]>;
}, `${string}/${string}`>>
error
.error);
error: "INTERNAL_SERVER_ERROR" | "USER_NOT_FOUND" | "VALIDATION_FAILED"
} else {
console.log(
const data: {
id: number;
name: string;
}
data
.
name: string
name
);
}

error is the body of any other status the document lists, including the 422 and 500 the framework answers. Branch on its error code. A refusal from a hook is in the document only when the hook is documented. To commit the document and check it in CI, as with the contract, see Using the document directly.