Thuta Learning
TypeScript
AdvancedProgrammingintermediate

Async APIs, Errors & Runtime Validation

TypeScriptသင်ခန်းစာ 22

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Async APIs, Errors & Runtime Validation ရဲ့ runtime value နဲ့ compile-time type ဆက်နွယ်မှုကိုရှင်းပြနိုင်ရန်
  • Strict mode တွင် unsafe input နဲ့ edge cases စမ်းနိုင်ရန်
  • Maintainable TypeScript contracts ရေးနိုင်ရန်

Async APIs, Errors & Runtime Validation ကို compiler-only concern မဟုတ်ဘဲ module resolution, runtime validation, declaration output, incremental builds, CI နဲ့ package boundaries တို့ပါသော system အဖြစ်တည်ဆောက်ပါ။ TypeScript types သည် runtime တွင်ဖျက်သွားသည်ကိုအမြဲမှတ်ထားပါ။

ပိုပြီးနားလည်ထားရမယ့် အချက်

Async APIs, Errors & Runtime Validation ကို compiler-only concern မဟုတ်ဘဲ module resolution, runtime validation, declaration output, incremental builds, CI နဲ့ package boundaries တို့ပါသော system အဖြစ်တည်ဆောက်ပါ။ TypeScript types သည် runtime တွင်ဖျက်သွားသည်ကိုအမြဲမှတ်ထားပါ။

လက်တွေ့မှာ ဘယ်လိုအသုံးချမလဲ

Async APIs, Errors & Runtime Validation example ကို strict mode ဖြင့် type-check လုပ်ပြီး valid, null/undefined, malformed API data, union variant အသစ်နဲ့ module boundary cases စမ်းပါ။ Type error ကို assertion သို့ any ဖြင့်ပိတ်မထားဘဲ contract သို့ validation ကိုပြင်ပါ။

ဒီသင်ခန်းစာပြီးရင်

typescript
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';
}

async function loadUser(): Promise<User> {
  const value: unknown = await fetch('/api/user').then(r => r.json());
  if (!isUser(value)) throw new Error('Invalid user response');
  return value;
}
You should see
Untrusted JSON ကိုစစ်ပြီးမှ User type အဖြစ်သုံးမည်။

ကိုယ်တိုင်စမ်းကြည့်ရန်

Async APIs, Errors & Runtime Validation example ကို strict mode ဖြင့် type-check လုပ်ပြီး valid, null/undefined, malformed API data, union variant အသစ်နဲ့ module boundary cases စမ်းပါ။ Type error ကို assertion သို့ any ဖြင့်ပိတ်မထားဘဲ contract သို့ validation ကိုပြင်ပါ။

Type Safety သတိပေးချက်

TypeScript compile အောင်ရုံဖြင့် API data နဲ့ runtime behavior မှန်ပြီဟုယူဆခြင်း။

NarrowingTypeScript

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • TypeScript compile အောင်ရုံဖြင့် API data နဲ့ runtime behavior မှန်ပြီဟုယူဆခြင်း။
  • Error ကို any, as သို့ non-null assertion ဖြင့်ဖျောက်ပြီး contract မပြင်ခြင်း။

လက်တွေ့လေ့ကျင့်ခန်း

Async APIs, Errors & Runtime Validation example ကို strict mode ဖြင့် type-check လုပ်ပြီး valid, null/undefined, malformed API data, union variant အသစ်နဲ့ module boundary cases စမ်းပါ။ Type error ကို assertion သို့ any ဖြင့်ပိတ်မထားဘဲ contract သို့ validation ကိုပြင်ပါ။

You'll know it worked when: Untrusted JSON ကိုစစ်ပြီးမှ User type အဖြစ်သုံးမည်။