- 最終更新
- 2026/10/21
3秒でわかる
API のリクエストやレスポンスの型を、フロントとバックエンドで同じ定義から参照する手法。片方だけ直したときのずれをコンパイル時に検出できる。
30秒図解
もう少し詳しく
どういうものか
API で
同じ形を 2 回書かない
なぜ必要か
API のname を fullName にuser.name は
型を
具体例
共有パッケージに
// packages/shared/src/api.ts
export type User = {
id: number;
fullName: string;
email: string;
};
export type GetUsersResponse = {
users: User[];
total: number;
};// apps/api/src/routes/users.ts
import type { GetUsersResponse } from "@app/shared";
app.get("/users", async (req, res) => {
const users = await db.user.findMany();
const body: GetUsersResponse = { users, total: users.length };
res.json(body);
});// apps/web/src/api/users.ts
import type { GetUsersResponse } from "@app/shared";
export async function fetchUsers(): Promise<GetUsersResponse> {
const res = await fetch("/api/users");
return res.json();
}Zod のような
import { z } from "zod";
export const userSchema = z.object({
id: z.number(),
fullName: z.string(),
email: z.string().email(),
});
export type User = z.infer<typeof userSchema>;つまずきやすいところ
import type にfetch の似た用語との違い
| 手法 | 型の出どころ |
|---|---|
| 型定義の共有 | 手で |
| スキーマからの生成 | Zod や |
| tRPC | サーバーの |
下に

