TypeScript แชร์ type ระหว่าง client กับ server



ปัญหา: server กำหนด shape ของ API — client ต้องเดา/เขียน type ซ้ำ พอ API เปลี่ยน client พังตอน runtime (ไม่ใช่ compile)

เป้าหมาย: type เดียว, source เดียว, ทั้งสองฝั่งใช้ — API เปลี่ยน → client compile error ทันที

วิธี 1: แชร์ package ใน monorepo

my-project/
├── package.json           (workspaces)
├── packages/
│   ├── shared/            @my-project/shared
│   │   ├── package.json
│   │   └── src/
│   │       ├── types.ts
│   │       └── schemas.ts
│   ├── server/            @my-project/server
│   └── web/               @my-project/web
// package.json (root)
{
  "workspaces": ["packages/*"]
}
// packages/shared/src/schemas.ts
import { z } from "zod";

export const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
});
export type User = z.infer<typeof UserSchema>;

export const CreateUserSchema = UserSchema.omit({ id: true });
export type CreateUser = z.infer<typeof CreateUserSchema>;
// packages/server/src/routes/users.ts
import { CreateUserSchema, type User } from "@my-project/shared";

app.post("/users", (req, res) => {
  const input = CreateUserSchema.parse(req.body);   // validate ด้วย schema เดียวกับ client
  const user: User = createUser(input);
  res.json(user);
});
// packages/web/src/api.ts
import { UserSchema, type User, type CreateUser } from "@my-project/shared";

async function createUser(data: CreateUser): Promise<User> {
  const res = await fetch("/api/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  return UserSchema.parse(await res.json());   // validate response ด้วย schema เดียวกัน
}

source เดียว (schemas.ts) — server และ client ใช้ type + validation ตัวเดียวกัน แก้ schema → ทั้งคู่ update

วิธี 2: tRPC — type ไหลจาก server

tRPC ไม่มี REST layer — client เรียก server procedure เหมือนเรียก function local, type ไหลผ่านอัตโนมัติ

// server/router.ts
import { initTRPC } from "@trpc/server";
import { z } from "zod";

const t = initTRPC.create();

export const appRouter = t.router({
  user: t.router({
    getById: t.procedure
      .input(z.object({ id: z.string() }))
      .query(({ input }) => {
        return db.user.findById(input.id);   // return type infer
      }),

    create: t.procedure
      .input(z.object({ name: z.string(), email: z.string().email() }))
      .mutation(({ input }) => {
        return db.user.create(input);
      }),
  }),
});

export type AppRouter = typeof appRouter;   // export "type ของ API ทั้งหมด"
// client — import แค่ type
import type { AppRouter } from "../server/router.js";
import { createTRPCClient, httpBatchLink } from "@trpc/client";

const trpc = createTRPCClient<AppRouter>({
  links: [httpBatchLink({ url: "http://localhost:3000/trpc" })],
});

// เรียกเหมือน function — type-safe เต็มที่
const user = await trpc.user.getById.query({ id: "u1" });
//    ^ type infer จาก server return

await trpc.user.create.mutate({ name: "อร", email: "a@b.com" });
await trpc.user.create.mutate({ name: "อร" });   // Error: ขาด email

เปลี่ยน server procedure → client compile error ทันที — ไม่มี type เขียนซ้ำที่ไหนเลย

ใช้กับ React ผ่าน @trpc/react-query (integrate TanStack Query):

const { data, isLoading } = trpc.user.getById.useQuery({ id: "u1" });

ข้อจำกัด tRPC: client กับ server ต้องเป็น TypeScript ทั้งคู่ และอยู่ใน repo/build เดียวกัน (หรือ publish type) — ไม่เหมาะกับ public API ที่ third-party ใช้

วิธี 3: OpenAPI → generate types

server มี OpenAPI spec (จาก decorator, schema, หรือเขียนเอง) → generate client types:

npx openapi-typescript https://api.example.com/openapi.json -o src/api-types.ts
import type { paths } from "./api-types.js";

type GetUserResponse = paths["/users/{id}"]["get"]["responses"]["200"]["content"]["application/json"];

หรือ generate ทั้ง client (openapi-fetch, orval, @hey-api/openapi-ts):

import createClient from "openapi-fetch";
import type { paths } from "./api-types.js";

const client = createClient<paths>({ baseUrl: "https://api.example.com" });

const { data, error } = await client.GET("/users/{id}", {
  params: { path: { id: "u1" } },
});
// data typed จาก spec

ใช้เมื่อ: server ไม่ใช่ TS, มี public API, หรือทีม backend/frontend แยกกัน

เปรียบเทียบ

วิธีclient/server ต้อง TSthird-party ใช้ได้effort
shared package (zod)client ควรclient ต้อง TSต่ำ-กลาง
tRPCทั้งคู่ไม่ต่ำ (แต่ผูก tRPC)
OpenAPI generateserver ไม่ต้องได้กลาง (มี spec)

เริ่มต้น: shared zod schema ใน monorepo — ง่าย, ไม่ผูก framework, validate ด้วย

ตั้งค่า monorepo (pnpm — แนะนำ)

# pnpm-workspace.yaml
packages:
  - "packages/*"
// packages/web/package.json
{
  "dependencies": {
    "@my-project/shared": "workspace:*"
  }
}
// tsconfig.json (แต่ละ package) — project references
{
  "references": [{ "path": "../shared" }]
}

เรื่องที่คนมักพลาด

  • เขียน type ของ API response ที่ client แยกจาก server — drift; แชร์ schema
  • แชร์ type แต่ไม่แชร์ validation — client เชื่อ type แต่ server ส่งผิด runtime; แชร์ zod schema (type + validate)
  • tRPC สำหรับ public API — client ต้อง TS + build เดียวกัน; ใช้ REST/OpenAPI
  • import server code เข้า client (ไม่ใช่ import type) — server code (db, secret) หลุดไป bundle
  • OpenAPI spec ที่ไม่ตรงกับ implementation — generate type ผิด; generate spec จากโค้ด
  • monorepo ไม่มี project references — tsc build ไม่รู้ dependency order

สรุป

  • เป้าหมาย: type + validation จาก source เดียว, client + server ใช้ร่วม — API เปลี่ยน = compile error
  • shared zod schema (monorepo) — z.infer เป็น type, .parse() validate ทั้งสองฝั่ง — เริ่มต้นที่ดี
  • tRPC — export type AppRouter = typeof router, client import type แล้วเรียกเหมือน function local; ทั้งคู่ต้อง TS
  • OpenAPI → openapi-typescript / openapi-fetch — เมื่อ server ไม่ใช่ TS / public API
  • import type เท่านั้นเมื่อดึงจาก server (ไม่ให้ code หลุดไป client bundle)

จบเฟสเฟรมเวิร์ก บทถัดไปเข้าเฟสโปรเจกต์ เริ่มที่ to-do CLI