TypeScript ข้อมูลจากภายนอกและ runtime validation
ปัญหา: JSON.parse คืน any
const data = JSON.parse(jsonString);
// data: any ← type check หลุดตั้งแต่นี้!
data.user.name.toUpperCase(); // ไม่มีใครเตือน — crash ถ้า structure ไม่ตรงJSON.parse return type เป็น any — ทุกอย่างที่ต่อจากนี้ไม่ถูกตรวจ
as ไม่ช่วย — type หายตอน compile
interface User {
id: number;
name: string;
email: string;
}
const user = JSON.parse(json) as User; // ⚠️ แค่ "บอก" TS ว่าเป็น User
user.name.toUpperCase(); // TS เชื่อ — แต่ถ้า json ไม่มี name → crashtype ของ TypeScript หายไปหมดตอน compile — ตอน runtime ไม่มีการเช็คว่า user มี name จริง as User = คำสัญญาที่ไม่มีใครบังคับ
ข้อมูลที่ “type ไม่ garantee”:
- API response — server ส่งอะไรมาก็ได้ (bug, version mismatch)
localStorage/sessionStorage— string, อาจถูกแก้, อาจเป็น format เก่า- form input / URL params — string เสมอ, ผู้ใช้พิมพ์อะไรก็ได้
- environment variables — string | undefined
- file content — format อาจผิด
วิธีที่ 1: type guard เขียนเอง
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value && typeof value.id === "number" &&
"name" in value && typeof value.name === "string" &&
"email" in value && typeof value.email === "string"
);
}
const parsed: unknown = JSON.parse(json);
if (isUser(parsed)) {
parsed.name.toUpperCase(); // ปลอดภัยแล้ว (type + runtime ตรงกัน)
} else {
throw new Error("response ไม่ตรงรูปแบบ User");
}ใช้ได้ แต่:
- verbose มากเมื่อ nested/หลาย field
- type guard กับ type definition แยกกัน → ต้อง sync เอง (แก้ interface แล้วลืมแก้ guard)
- TS ไม่ตรวจว่า guard logic ตรงกับ
Userจริง
วิธีที่ 2: zod — schema เป็น source of truth
npm install zodimport { z } from "zod";
const UserSchema = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
email: z.string().email(),
role: z.enum(["admin", "editor", "viewer"]).default("viewer"),
createdAt: z.string().datetime().optional(),
});
// infer TypeScript type จาก schema — ไม่ต้องเขียน interface แยก!
type User = z.infer<typeof UserSchema>;
// { id: number; name: string; email: string; role: "admin" | "editor" | "viewer"; createdAt?: string }parse + validate:
const parsed: unknown = JSON.parse(json);
// throw ZodError ถ้าไม่ตรง
const user = UserSchema.parse(parsed); // user: User (validated!)
// หรือไม่ throw
const result = UserSchema.safeParse(parsed);
if (result.success) {
result.data.name; // User
} else {
console.error(result.error.issues);
// [{ path: ["email"], message: "Invalid email", ... }]
}schema เป็น source of truth เดียว — type (z.infer) และ runtime validation มาจากที่เดียว แก้ schema → ทั้งคู่อัปเดต
zod กับ fetch
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const json: unknown = await res.json();
return UserSchema.parse(json); // ← validate ที่ boundary
}
// ตอนนี้ทุกที่ที่ใช้ผลจาก fetchUser มั่นใจได้ว่า type ตรง runtimevalidate ที่ boundary (จุดที่ข้อมูลเข้าระบบ) — ข้างในไม่ต้องกังวลอีก
zod กับ environment variables
const EnvSchema = z.object({
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().default(3000), // "3000" → 3000
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
});
export const env = EnvSchema.parse(process.env);
// env: { DATABASE_URL: string; PORT: number; NODE_ENV: ...; LOG_LEVEL: ... }
// crash ตอน startup พร้อมข้อความชัด ถ้า env ขาด/ผิดzod transform และ refine
const DateSchema = z.string().transform((s) => new Date(s)); // string → Date
const PasswordSchema = z
.object({ password: z.string(), confirm: z.string() })
.refine((data) => data.password === data.confirm, {
message: "รหัสผ่านไม่ตรงกัน",
path: ["confirm"],
});ทางเลือกอื่น
- valibot — เล็กกว่า zod, tree-shakeable
- arktype — syntax คล้าย TS type
- typia — compile-time validation (เร็วมาก, ต้อง plugin)
- @sinclair/typebox — JSON Schema + type
zod เป็นตัวที่นิยมที่สุด — ecosystem ใหญ่ (tRPC, React Hook Form, Astro ใช้)
เรื่องที่คนมักพลาด
JSON.parse(x) as User— ไม่ validate; ใช้ zod หรือ type guard- เชื่อ API response ตาม type ที่เขียน — server เปลี่ยน / bug / null field ที่ไม่คาด
localStorage.getItemแล้วJSON.parseแล้วใช้เลย — อาจ null, อาจ format เก่า- validate ทุก layer — validate ที่ boundary ครั้งเดียวพอ
- เขียน interface แยกจาก zod schema — ใช้
z.infer<typeof Schema>ให้ sync กัน process.env.PORTใช้เป็น number — เป็นstring | undefined;z.coerce.number()z.string()แล้วคาดว่ากรอง""— ต้อง.min(1)
สรุป
JSON.parseคืนany— type check หลุด; รับเป็นunknownแล้ว validate- type ของ TS หายตอน compile —
as Userไม่ตรวจ runtime; ข้อมูลจาก API/storage/form/env อาจไม่ตรง - validate ด้วย: type guard เขียนเอง (verbose, sync เอง) หรือ zod (schema = source of truth)
- zod:
z.object({...})→.parse()(throw) /.safeParse()(result) +z.infer<typeof Schema>= type - validate ที่ boundary (fetch, env, storage) ครั้งเดียว — ข้างในมั่นใจได้
z.coerce.number()สำหรับ env vars,.transform()/.refine()สำหรับ logic
จบเฟสเขียนโค้ดจริง บทถัดไปเข้าเฟสเครื่องมือ เริ่มที่ tsconfig.json เจาะลึก