Skip to content

Commit

Permalink
docs(types): add type helper documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
ecyrbe committed Oct 10, 2022
1 parent 97d9387 commit 847591f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 15 deletions.
15 changes: 0 additions & 15 deletions website/docs/client/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -657,18 +657,3 @@ const apiClient = new Zodios(BASE_URL, [
},
]);
```

## Passing types around

Sometimes, you might need an endpoint-related type (it could be its query params, body, response, etc...) in another place than the one where you're using the API client.
In such case, there are plenty of utility-types provided out-of-the-box.

Re-using the [CRUD helper](#crud-helper) example above, here are some examples on how to retrieve any type of an endpoint.


```ts
import type { Body } from '@zodios/core';

type UserList = Response<typeof apiClient.api, "get", "/users">
type PatchUserBody = Body<typeof apiClient.api, "patch", "/users/:id">
```
49 changes: 49 additions & 0 deletions website/docs/client/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
sidebar_position: 5
---

# Typescript

Even though zodios is written in typescript, you can use it with javascript. However, if you are using typescript, you can benefit from the typescript type helpers.

## Example

```ts
import {
makeCrudApi,
Response,
Body,
PathParams,
QueryParams,
} from "../src/index";
import z from "zod";

const user = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
phone: z.string(),
});

const api = makeCrudApi("user", user);

type User = z.infer<typeof user>;
type Api = typeof api;

type Users = Response<Api, "get", "/users">;
// ^? type Users = { id: number; name: string; email: string; phone: string; }[]
type UserById = Response<Api, "get", "/users/:id">;
// ^? type UserById = { id: number; name: string; email: string; phone: string; }
type GetUserParams = PathParams<"/users/:id">;
// ^? type GetUserParams = { id: string; }
type GetUserQueries = QueryParams<Api, "get", "/users/:id">;
// ^? type GetUserQueries = never
type CreateUserBody = Body<Api, "post", "/users">;
// ^? type CreateUserBody = { name: string; email: string; phone: string; }
type CreateUserResponse = Response<Api, "post", "/users">;
// ^? type CreateUserResponse = { id: number; name: string; email: string; phone: string; }
type UpdateUserBody = Body<Api, "put", "/users/:id">;
// ^? type UpdateUserBody = { name: string; email: string; phone: string; }
type PatchUserBody = Body<Api, "patch", "/users/:id">;
// ^? type PatchUserBody = { name?: string | undefined; email?: string | undefined; phone?: string | undefined; }
```

0 comments on commit 847591f

Please sign in to comment.