Skip to content

Type safety ​

An endpoint's Zod schemas are the only place its types are written. The handler's arguments, its return value, the generated client's requests and its responses are all inferred from them, so a change to a schema is checked everywhere it matters, on the server and in the front end.

Every code sample on this page is compiled against the library when the site is built. The types and errors shown are the compiler's own. Hover over any name to see its type.

The handler's arguments ​

input, query and params reach the handler as the parsed output of their schemas: coerced, defaulted and narrowed.

ts
export default 
endpoint
.
query
({
params
:
z
.
object
({
orderId
:
z
.
coerce
.
number
() }),
query
:
z
.
object
({
include
:
z
.
enum
(['items', 'customer']).
optional
(),
draft
:
z
.
stringbool
().
default
(false),
}),
handler
: ({
params
,
query
}) => {
params;
params: {
    orderId: number;
}
query;
query: {
    draft: boolean;
    include?: "items" | "customer" | undefined;
}
return {
ok
: true };
}, });

orderId arrives in the URL as a string and reaches the handler as a number. draft has a default, so it is always a boolean.

What you inject is typed as well, from the provider's class or from the type you give decorated<T>():

ts
export default 
endpoint
.
mutation
({
input
:
z
.
object
({
orderId
:
z
.
number
(),
reason
:
z
.
string
() }),
inject
: {
payments
:
PaymentsService
},
injectOnRequest
: {
user
:
decorated
<
User
>(
CurrentUser
()) },
handler
: ({
input
,
payments
, user }) =>
user: User
payments
.
refund
(
input
.
orderId
,
input
.
reason
,
user
.
id
),
});

The return value ​

The handler's return type is checked against output. A value of the wrong shape doesn't compile:

ts
export default 
endpoint
.
query
({
params
:
z
.
object
({
orderId
:
z
.
coerce
.
number
() }),
output
:
z
.
object
({
id
:
z
.
number
(),
status
:
z
.
enum
(['pending', 'paid', 'cancelled']),
total
:
z
.
number
(),
}),
handler
: ({
params
}) => ({
id
:
params
.
orderId
,
status: 'refunded',
Type 'string' is not assignable to type '"pending" | "paid" | "cancelled"'.
total
: 25,
}), });

A missing field is an error in the same way.

A return value may carry more than output declares. Those keys are not a type error: they are stripped when the response is parsed.

In a block body ​

In a handler with a block body (=> { … return … }), TypeScript reports a wrong value on the handler property, in a long message whose last line names the field (microsoft/TypeScript#42161). To have the error on the value, annotate the return type with z.input of the schema:

ts
const 
order
=
z
.
object
({
id
:
z
.
number
(),
status
:
z
.
enum
(['pending', 'paid', 'cancelled']),
total
:
z
.
number
(),
}); export default
endpoint
.
query
({
params
:
z
.
object
({
orderId
:
z
.
coerce
.
number
() }),
output
:
order
,
handler
: async ({
params
}):
Promise
<
z
.
input
<typeof
order
>> => {
return {
id
:
params
.
orderId
, status: 'refunded',
total
: 25 };
Type '"refunded"' is not assignable to type '"pending" | "paid" | "cancelled"'.
}, });

An object literal with a key output doesn't declare is then an error too, though a value from a variable or a call may still carry more.

Status codes ​

With a schema per status, the handler returns response(status, body). The status must be one output declares, and the body is checked against that status's schema:

ts
export default 
endpoint
.
mutation
({
input
:
z
.
object
({
email
:
z
.
email
() }),
output
: {
201:
z
.
object
({
id
:
z
.
number
() }),
409:
z
.
object
({
message
:
z
.
string
() }),
},
handler
: ({
input
,
response
}) =>
input
.
email
.
endsWith
('@example.com')
?
response
(409, {
message
: 'Already registered' })
:
response
(201, { id: 'not-a-number' }),
Type 'string' is not assignable to type 'number'.
});

Both are arguments of a call, so a mismatch is reported on the value itself, in a block body too.

The client ​

The generated clients are typed from the same schemas. Operations autocomplete, under the namespaces your routers declare:

ts
const 
client
=
createApiClient
({
baseURL
: '/api' });
client
.
orders
.

A request that doesn't match the endpoint's schemas doesn't compile:

ts
await 
client
.
orders
.
create
({
body
: {
productId
: 'sku_42', quantity: '2' },
Type 'string' is not assignable to type 'number'.
}); await
client
.
orders
.
view
({
path
: { orderId: 'first' } });
Type 'string' is not assignable to type 'number'.
// a path parameter can't be left out await
client
.
orders
.view();
Expected 1 arguments, but got 0.

A call resolves to the response with its status, and data is the endpoint's output:

ts
const 
result
= await
client
.
orders
.
create
({
body
: {
productId
: 'sku_42',
quantity
: 2 },
}); result;
const result: {
    status: 200;
    data: OrdersCreateOutput;
    error: undefined;
    contentType: string | undefined;
    headers: HeadersFor<unknown, "200">;
    request: NativeRequest;
    response: NativeResponse;
}
// the body alone const
order
= await
client
.
orders
.
create
({
body
: {
productId
: 'sku_42',
quantity
: 2 },
}).
unwrap
();

Comparing a response with a value the server can never send is an error too:

ts
if (order.status === 'refunded') {
This comparison appears to be unintentional because the types 'OrdersViewOutputStatusEnumKey' and '"refunded"' have no overlap.
// … }

The React Query hooks carry the same types. A query's data is its output, and a mutation's variables are its request:

tsx
const 
client
=
useApiClient
();
const
order
=
client
.
orders
.
useView
({
path
: {
orderId
} });
order
.
data
?.
tsx
const 
create
=
client
.
orders
.
useCreate
();
create
.
mutate
({
body
: { productId: 42,
quantity
: 2 } });
Type 'number' is not assignable to type 'string'.

Tests ​

An endpoint's invoke() runs it without HTTP, and resolves to the type of its output:

ts
const 
created
= await
app
.
get
(
createOrder
).
invoke
({
productId
: 'sku_42',
quantity
: 2,
}); created;
const created: {
    id: number;
    status: "pending" | "paid" | "cancelled";
}

Keeping the client in step ​

With setupCodegen in your main.ts and a dev server that restarts on change, saving an endpoint file regenerates the client, and any caller the change broke shows up as a type error in the front end.

Released under the MIT License.