ရိုးရိုးလေး ရှင်းပြမယ်
Runtime validation ကို ရိုးရိုးလေး ပြောရရင်
TypeScript type တွေက တံခါးမှာ ကပ်ထားတဲ့ 'ဝန်ထမ်းများသာ' ဆိုင်းဘုတ်လိုပါပဲ: ကိုယ့်အဖွဲ့သားတွေ စည်းကမ်းလိုက်နာဖို့ ကူညီပေမဲ့ အပြင်လူကို တကယ် မတားနိုင်ပါဘူး။ Code run တဲ့အချိန်မှာ type တွေ မရှိတော့ပါဘူး၊ ဒါကြောင့် server, file ဒါမှမဟုတ် user ဆီက ရောက်လာတဲ့ data ကို တံခါးစောင့်တစ်ယောက်က စစ်ပေးဖို့ လိုပါတယ်။
Runtime validation က အဲဒီ တံခါးစောင့်ပါ — data ရဲ့ shape ကို တကယ် စစ်တဲ့ code လေးတစ်ခုပါ။ စစ်ပြီးမှ data ကို typed value အဖြစ် program ထဲ ဝင်ခွင့်ပေးပါတယ်။ Async code မှာ အဲဒီ စစ်ဆေးမှုက promise ထဲမှာ ဖြစ်တဲ့အတွက် error တွေကိုလည်း မှန်မှန်ကန်ကန် ဖမ်းတတ်ဖို့ လိုပါတယ်။
Problem → Why → Solution
ပြဿနာ: ဘယ်သူမှ မစစ်တဲ့ annotation
Dashboard တစ်ခုက GET /api/user ကို ခေါ်ပြီး ရလဒ်ကို User လို့ annotate လုပ်ထားပါတယ်။ လအနည်းငယ်ကြာတော့ backend က name ကို fullName လို့ နာမည်ပြောင်းလိုက်ပါတယ်။ Frontend က compile ဖြစ်နေတုန်းပဲ၊ mock data နဲ့ test တွေလည်း pass နေတုန်းပဲ၊ production မှာတော့ header က "Hello, undefined" လို့ ပြတယ်၊ ဒါမှမဟုတ် user.name.toUpperCase() ကို ခေါ်တဲ့နေရာမှာ crash ဖြစ်ပါတယ်။ Annotation က ဘယ်သူမှ မစစ်တဲ့ ကတိတစ်ခုသာ ဖြစ်တဲ့အတွက် ဘာမှ သတိပေးမယ့်သူ မရှိခဲ့ပါဘူး။
type User = { id: string; name: string };
async function loadUser(): Promise<User> {
const response = await fetch("/api/user");
const user: User = await response.json(); // any -> User, never checked
return user;
}
// The server now sends { id: "u1", fullName: "Ada" }
const user = await loadUser();
console.log(user.name.toUpperCase()); // TypeError at runtimeဘာကြောင့် ဒါက အန္တရာယ်ရှိတာလဲ
response.json() ပေါ်က annotation က check မဟုတ်ပါဘူး၊ any ကို assertion နဲ့ User အဖြစ် ပြောင်းလိုက်တာပါပဲ။ TypeScript က network ကို မမြင်နိုင်တဲ့အတွက် shape ကို အတည်ပြုနိုင်တာ run တဲ့ code တစ်ခုတည်းပါ။ Boundary မှာ validate လုပ်လိုက်ရင် UI အနက်ပိုင်းက နားမလည်နိုင်တဲ့ crash ကို data မှားဝင်လာတဲ့ နေရာအတိအကျမှာ 'Invalid user response' ဆိုတဲ့ ရှင်းလင်းတဲ့ error အဖြစ် ပြောင်းပေးပါတယ်။
Core concept: edge မှာ parse လုပ်ပြီး typed data ကို အတွင်းထဲ စီးဆင်းစေပါ
TypeScript type တွေက compile လုပ်နေတုန်းမှာပဲ ရှိပါတယ်။ Run တဲ့ JavaScript က User ဆိုတာ ဘာလဲ မသိတဲ့အတွက် server က { id: 42 } ဒါမှမဟုတ် HTML error page ပို့တာကို runtime မှာ ဘာမှ မတားပါဘူး။ fetch response, JSON.parse, localStorage, form, message queue ဒါမှမဟုတ် process.env လို အပြင်ကနေ program ထဲ ဝင်လာသမျှကို code က မစစ်မချင်း unknown အဖြစ် ဆက်ဆံသင့်ပါတယ်။
Standard DOM type တွေမှာ response.json() ကို Promise<any> လို့ type ပေးထားပါတယ်၊ ဒါကြောင့် const user: User = await response.json() က ဘာမှ မညည်းဘဲ compile ဖြစ်ပါတယ် — any ကို ဘယ် type ထဲမဆို assign လုပ်လို့ ရလို့ပါ။ အဲဒီအစား ရလဒ်ကို unknown လို့ annotate လုပ်ပါ။ unknown က မသုံးခင် narrow လုပ်ဖို့ အတင်းတောင်းပြီး narrow လုပ်တဲ့နေရာက သင့် validation boundary ဖြစ်လာပါတယ်။ fetch က network ပျက်မှပဲ reject ဖြစ်တာကိုလည်း မှတ်ထားပါ — 404 ဒါမှမဟုတ် 500 က resolve ဖြစ်နေဆဲမို့ body ကို မဖတ်ခင် response.ok ကို စစ်ပါ။
async function က Promise ကို အမြဲ ပြန်ပေးပါတယ်။ အထဲမှာ throw လုပ်လိုက်ရင် rejected promise ဖြစ်သွားပြီး ခေါ်သူက try/catch ထဲမှာ await လုပ်မှ (ဒါမှမဟုတ် .catch ချိတ်မှ) အဲဒီ error ကို မြင်ရပါတယ်။ JavaScript က Error object တွေချည်း မဟုတ်ဘဲ ဘာမဆို throw လုပ်လို့ ရတဲ့အတွက် strict mode မှာ catch variable က unknown ဖြစ်ပါတယ် (useUnknownInCatchVariables option)၊ message ကို မဖတ်ခင် error instanceof Error နဲ့ narrow လုပ်ပါ။
| Source | Type | ဘာလုပ်ရမလဲ |
|---|---|---|
| response.json() | Promise<any> | unknown လို့ annotate လုပ်ပြီး validate လုပ် |
| JSON.parse(text) | any | unknown လို့ annotate လုပ်ပြီး validate လုပ် |
| catch (error) | unknown (strict) | instanceof Error နဲ့ narrow လုပ် |
Validate လုပ်ဖို့ အသုံးများတဲ့ နည်းလမ်း နှစ်ခု ရှိပါတယ်။ လက်ရေး type guard (value is User) က dependency မလိုဘဲ shape သေးသေးလေးတွေနဲ့ ကိုက်ပါတယ်။ zod လို schema library ကတော့ shape ကို တစ်ကြိမ်တည်း ဖော်ပြပြီး runtime မှာ စစ်ပေး၊ z.infer နဲ့ static type ကိုပါ derive လုပ်ပေးလို့ check နဲ့ type ကွဲထွက်သွားလို့ မရပါဘူး။ ဘယ်နည်းပဲ သုံးသုံး စည်းမျဉ်းက အတူတူပါ: edge မှာ parse လုပ်ပြီးမှ typed data ကို အတွင်းထဲ စီးဆင်းစေပါ။
- အပြင် data က unknown အဖြစ် ရောက်လာ
- Status စစ်ပြီးမှ body ကို parse
- Guard ဒါမှမဟုတ် schema နဲ့ validate
- စစ်ပြီးသား data ကိုပဲ type ပေး
Compiler က သင့် type တွေကို ယုံပါတယ်၊ runtime မှာ အဲဒီ type တွေ တကယ်မှန်အောင် လုပ်ပေးတာက validation ပါ။
အထွေထွေ ပုံစံ
async function loadThing(url: string): Promise<Thing> {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data: unknown = await response.json();
if (!isThing(data)) throw new Error("Invalid response");
return data; // narrowed to Thing by the guard
}HTTP status ကို အရင်စစ်၊ body ကို unknown အဖြစ် parse လုပ်၊ guard ဒါမှမဟုတ် schema နဲ့ validate လုပ်ပြီးမှ return ပြန်ပါ။ မှားရင် ရှင်းလင်းတဲ့ message ပါတဲ့ error ကို throw လုပ်ပါ။
Worked example: type guard နဲ့ user ကို load လုပ်ခြင်း
Network မလိုဘဲ Node မှာ run နိုင်အောင် fakeFetch က တကယ့် Response object တစ်ခုကို ဆောက်ပေးပါတယ်၊ ကျန်တာက တကယ့် fetch code နဲ့ အတူတူပါပဲ။ main က မှန်တဲ့ body တစ်ခု၊ shape မှားတဲ့ body တစ်ခုနဲ့ HTTP 500 တစ်ခုကို စမ်းကြည့်ပါတယ်။
type User = { id: string; name: string };
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const record = value as Record<string, unknown>;
return typeof record.id === "string" && typeof record.name === "string";
}
// A stand-in for fetch so the example runs offline in Node
async function fakeFetch(body: string, status = 200): Promise<Response> {
return new Response(body, { status });
}
async function loadUser(body: string, status?: number): Promise<User> {
const response = await fakeFetch(body, status);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const value: unknown = await response.json();
if (!isUser(value)) throw new Error("Invalid user response");
return value;
}
async function main() {
const user = await loadUser('{"id":"u1","name":"Ada"}');
console.log("ok:", user.name);
for (const [body, status] of [['{"id":42}', 200], ["{}", 500]] as const) {
try {
await loadUser(body, status);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log("rejected:", message);
}
}
}
main();Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- The type guard
function isUser(value: unknown): value is User {unknown ကို လက်ခံပြီး value is User ဆိုတဲ့ type predicate ကို ပြန်ပေးပါတယ်။ true ပြန်ရင် compiler က ခေါ်တဲ့နေရာမှာ value ကို User အဖြစ် narrow လုပ်ပေးပါတယ်။
- Check the status
if (!response.ok) throw new Error(`HTTP ${response.status}`);fetch က 500 မှာ reject မဖြစ်တဲ့အတွက် ကိုယ်တိုင် စစ်ရပါတယ်။ ဒါကြောင့် error page ကို parser ဆီ မပို့မိပါဘူး။
- Parse as unknown
const value: unknown = await response.json();any အစား unknown လို့ annotate လုပ်ထားလို့ value ကို guard မဖြတ်ခင် property ဖတ်တာ ဒါမှမဟုတ် return ပြန်တာ မလုပ်နိုင်ပါဘူး။
- Validate, then return
if (!isUser(value)) throw new Error("Invalid user response");ဒီ line ပြီးနောက် value က User ဖြစ်ပြီး Promise<User> အဖြစ် return လုပ်လို့ ရပါပြီ။ Shape မှားရင် error ကို data ဝင်လာတဲ့ နေရာမှာပဲ throw လုပ်ပါတယ်။
- Catch and narrow
const message = error instanceof Error ? error.message : String(error);await က try ထဲမှာ ရှိလို့ rejection ကို ဖမ်းမိပါတယ်။ error က unknown ဖြစ်လို့ message ကို မဖတ်ခင် instanceof Error နဲ့ narrow လုပ်ပါတယ်။
ok: Ada
rejected: Invalid user response
rejected: HTTP 500Schema တစ်ခုနဲ့ validate လုပ်ခြင်း (zod)
Field များလာတာနဲ့ လက်ရေး guard တွေက ရှည်လာပြီး type နဲ့ ကွဲထွက်ဖို့ လွယ်လာပါတယ်။ zod မှာတော့ schema ကို တစ်ကြိမ်ရေးပြီး type ကို အဲဒီကနေ derive လုပ်ပါတယ်။ safeParse က throw မလုပ်ဘဲ success flag ပါတဲ့ result ကို ပြန်ပေးပြီး error.issues ထဲမှာ ဘယ် field မှားလဲ path နဲ့ ပါပါတယ်။
import { z } from "zod";
const UserSchema = z.object({
id: z.string(),
name: z.string().min(1),
age: z.number().int().nonnegative().optional(),
});
type User = z.infer<typeof UserSchema>; // inferred: id, name, optional age
function parseUser(data: unknown): User | null {
const result = UserSchema.safeParse(data);
if (!result.success) {
const paths = result.error.issues.map((issue) => issue.path.join("."));
console.log("invalid fields:", paths.join(", "));
return null;
}
return result.data;
}
console.log(parseUser({ id: "u1", name: "Ada", age: 36 }));
parseUser({ id: 7, name: "", age: -1 }); // prints: invalid fields: id, name, ageUserSchema ကို ပြောင်းလိုက်တာနဲ့ User type လည်း လိုက်ပြောင်းပါတယ်၊ ဒါကြောင့် check နဲ့ type မကိုက်ညီတော့တဲ့ အခြေအနေ မဖြစ်တော့ပါဘူး။ Throw လုပ်တာကို ပိုကြိုက်ရင် parse ကို သုံးပါ၊ ဒါပေမဲ့ boundary မှာ safeParse က error ကို user-friendly message ဒါမှမဟုတ် HTTP 400 အဖြစ် ပြောင်းရ ပိုလွယ်ပါတယ်။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ ဘယ်နေရာတွေကို validate လုပ်ရမလဲ
Production app တိုင်းမှာ type မရှိတဲ့ data ဝင်လာတဲ့ boundary တွေ ရှိပါတယ်။ Validate လုပ်လေ့ရှိတဲ့ နေရာတွေကတော့:
- API client: response.ok ကို စစ်၊ JSON ကို unknown အဖြစ် parse လုပ်၊ schema run တဲ့ helper တစ်ခုထဲမှာ fetch ကို ထုပ်ထားပါ၊ ဒါမှ component တစ်ခုမှ raw JSON ကို မထိရပါဘူး။
- Server handler: request body နဲ့ query string တွေကို business logic ဆီ မရောက်ခင် validate လုပ်ပါ၊ အထဲနက်နက်ကနေ 500 ထွက်မယ့်အစား မှားတဲ့ field path တွေနဲ့ 400 ကို ပြန်ပေးပါ။
- Configuration: startup မှာ process.env ကို schema နဲ့ တစ်ကြိမ် parse လုပ်ပါ၊ ဒါမှ DATABASE_URL ပျောက်နေရင် ပထမ query ကျမှ မဟုတ်ဘဲ ချက်ချင်း ရှင်းလင်းတဲ့ message နဲ့ fail ဖြစ်ပါတယ်။
- သိမ်းထားတဲ့ data: localStorage, IndexedDB နဲ့ queue တွေထဲမှာ app ရဲ့ version အဟောင်းက ရေးခဲ့တဲ့ data ရှိနိုင်ပါတယ်၊ validate လုပ်ပြီး shape ပြောင်းသွားရင် default ကို ပြန်သုံးပါ။
အမှားများ
Async နဲ့ validation မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ
JSON ကို validate မလုပ်ဘဲ cast လုပ်ခြင်း
(await response.json()) as User နဲ့ User လို့ annotate လုပ်တာ အတူတူပါပဲ — assertion ဖြစ်ပြီး compile ဖြစ်ပေမဲ့ ဘာမှ မစစ်ပါဘူး။ unknown နဲ့ guard ဒါမှမဟုတ် schema ကို သုံးပါ။
fetch က HTTP error မှာ reject မဖြစ်တာကို မေ့ခြင်း
404 page ဒါမှမဟုတ် { error } body က သင့် parser ဆီ ရောက်လာပါလိမ့်မယ်။ response.ok (ဒါမှမဟုတ် response.status) ကို အရင်စစ်ပြီး အဓိပ္ပာယ်ရှိတဲ့ error အဖြစ် ပြောင်းပါ။
try/catch ထဲမှာ await မလုပ်ခြင်း
try { loadUser(); } catch {} က ဘာမှ မဖမ်းပါဘူး၊ promise က နောက်မှ reject ဖြစ်လို့ပါ။ try ထဲမှာ await loadUser() လို့ ရေးပါ၊ မဟုတ်ရင် error က unhandled rejection ဖြစ်သွားပါတယ်။
Narrow မလုပ်ဘဲ error.message ကို ဖတ်ခြင်း
Strict mode မှာ catch clause ထဲက error က unknown ဖြစ်ပါတယ်၊ ဒါကြောင့် error.message ဟာ compile error ပါ။ error instanceof Error ကို အရင်စစ်ပြီး မဟုတ်ရင် String(error) နဲ့ fallback လုပ်ပါ။
Best Practices
Best practices
- Validation ကို boundary တစ်နေရာတည်းမှာ ထားပါ၊ ပြီးရင် app ရဲ့ ကျန်တဲ့အပိုင်းက typed data ကို ယုံကြည်စွာ သုံးပါစေ။
- Error message ထဲမှာ ဘယ် endpoint နဲ့ ဘယ် field မှားလဲ ထည့်ပါ၊ production log တွေထဲမှာ ပြဿနာကို ချက်ချင်း ရှာတွေ့ပါတယ်။
- ခေါ်သူတိုင်းက ကိုင်တွယ်ရမယ့် မှားနိုင်ချေ result တွေအတွက် throw အစား { ok: true } | { ok: false } လို discriminated union ကို ပြန်ပေးပါ။
Mini challenge
Mini challenge: throw မလုပ်တဲ့ loadProducts
Shop page တစ်ခုအတွက် loadProducts ကို ရေးပါ။ Network မလိုဘဲ စမ်းလို့ရအောင် JSON ယူပေးတဲ့ function တစ်ခုကို လက်ခံပြီး zod နဲ့ data ကို validate လုပ်ကာ throw မလုပ်ဘဲ result object ကို ပြန်ပေးရပါမယ်၊ ဒါမှ page က product တွေ ဒါမှမဟုတ် error message ကို ပြနိုင်ပါတယ်။
- zod နဲ့ ProductSchema ကို define လုပ်ပြီး Product type ကို z.infer နဲ့ derive လုပ်ပါ
- အောင်မြင်ရင် { ok: true; products } ကို၊ မအောင်မြင်ရင် { ok: false; error } ကို ပြန်ပေးပါ
- Throw ဖြစ်တဲ့ error နဲ့ မမှန်တဲ့ data နှစ်မျိုးလုံးကို { ok: false } အဖြစ် ပြောင်းပါ
- မှန်တဲ့ payload, မှားတဲ့ payload နဲ့ service down ဖြစ်နေတဲ့ case တွေနဲ့ run ပြီး ရလဒ်ကို print ထုတ်ပါ
import { z } from "zod";
// TODO: id (string), name (non-empty string), price (number >= 0)
const ProductSchema = z.object({});
type Product = z.infer<typeof ProductSchema>;
type LoadResult =
| { ok: true; products: Product[] }
| { ok: false; error: string };
async function loadProducts(getJson: () => Promise<unknown>): Promise<LoadResult> {
// TODO: await getJson() inside try/catch and narrow the error
// TODO: validate an array of products with safeParse
// TODO: return the matching LoadResult
}
// TODO: call loadProducts with fake getJson functions and print each resultရလဒ်: မှန်တဲ့ payload က 1 product(s) ကို၊ price: -1 ပါတဲ့ payload က Invalid data at 0.price ကို၊ throw လုပ်တဲ့ getJson က Service unavailable ကို print ထုတ်ပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
Array တစ်ခုလုံးကို z.array(ProductSchema).safeParse(data) နဲ့ စစ်ပါ။ Error message ထဲမှာ issue.path.join(".") ကို ထည့်ရင် ဘယ် item ရဲ့ ဘယ် field မှားလဲ ပြနိုင်ပါတယ်။ Fake getJson ကို async () => [...] လို့ ရေးလို့ ရပါတယ်။
အဖြေ ကြည့်ရန်
import { z } from "zod";
const ProductSchema = z.object({
id: z.string(),
name: z.string().min(1),
price: z.number().nonnegative(),
});
type Product = z.infer<typeof ProductSchema>;
type LoadResult =
| { ok: true; products: Product[] }
| { ok: false; error: string };
async function loadProducts(getJson: () => Promise<unknown>): Promise<LoadResult> {
let data: unknown;
try {
data = await getJson();
} catch (error) {
const message = error instanceof Error ? error.message : "Network error";
return { ok: false, error: message };
}
const parsed = z.array(ProductSchema).safeParse(data);
if (!parsed.success) {
const where = parsed.error.issues.map((issue) => issue.path.join(".")).join(", ");
return { ok: false, error: `Invalid data at ${where}` };
}
return { ok: true, products: parsed.data };
}
async function main() {
const good = await loadProducts(async () => [{ id: "p1", name: "Pen", price: 2.5 }]);
const bad = await loadProducts(async () => [{ id: "p2", name: "Ink", price: -1 }]);
const down = await loadProducts(async () => {
throw new Error("Service unavailable");
});
for (const result of [good, bad, down]) {
console.log(result.ok ? `${result.products.length} product(s)` : result.error);
}
}
main();Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Type တွေ runtime မှာ ဖျက်ခံရလို့ အပြင်ကလာတဲ့ data ကို validate မလုပ်မချင်း unknown အဖြစ် ဆက်ဆံပါ။
- response.json() နဲ့ JSON.parse က any ကို ပြန်ပေးပါတယ်၊ annotation ဒါမှမဟုတ် as က check မဟုတ်ပါဘူး။
- Shape သေးရင် type guard ကို၊ check နဲ့ type တစ်ခုတည်းကနေ ထွက်စေချင်ရင် zod schema နဲ့ z.infer ကို သုံးပါ။
- response.ok ကို စစ်ပါ၊ try ထဲမှာ await လုပ်ပါ၊ unknown ဖြစ်တဲ့ catch variable ကို instanceof Error နဲ့ narrow လုပ်ပါ။
Narrowing — TypeScript