Thuta Learning
TypeScript
AdvancedProgrammingအလယ်အလတ်

Type Narrowing and Type Guards

TypeScriptသင်ခန်းစာ 1625 မိနစ်

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

  • Union Type ကို runtime condition နဲ့ safe ဖြစ်အောင်ခွဲသုံးနိုင်မယ်
  • typeof, in, instanceof နဲ့ Custom Type Guard ကိုရွေးသုံးနိုင်မယ်
  • API data ကို unknown မှစပြီး validate လုပ်နိုင်မယ်
  • Discriminated Union နဲ့ Exhaustive Checking ကိုရေးနိုင်မယ်

ရိုးရိုးလေး ရှင်းပြမယ်

Type Narrowing ကို အလွယ်နားလည်မယ်

Variable တစ်ခုမှာ ဖြစ်နိုင်တဲ့ Type အများကြီးရှိနေတဲ့အခါ condition နဲ့ စစ်ပြီး “ဒီနေရာမှာတော့ ဒီ Type ပဲဖြစ်နိုင်တယ်” လို့ TypeScript ကို သိစေတာ Type Narrowing ပါ။

အဓိကအချက်က value ကို Type အသစ်အဖြစ်ပြောင်းတာမဟုတ်ပါဘူး။ Runtime value ကိုစစ်ပြီး compiler ရဲ့ သိထားတဲ့ information ကိုပိုတိကျအောင်လုပ်တာပါ။

Problem → Why → Solution

ပြဿနာက ဘာလဲ

ဒီ function က string သို့မဟုတ် number လက်ခံနိုင်ပါတယ်။ ဒါပေမယ့် toUpperCase() ကို တိုက်ရိုက်ခေါ်ရင် TypeScript က error ပြပါတယ်။

typescript
function printValue(value: string | number) {
  console.log(value.toUpperCase())
}

ဘာကြောင့် error ဖြစ်တာလဲ

string မှာ toUpperCase() ရှိပေမယ့် number မှာမရှိပါဘူး။ value ရဲ့ Type ကိုမစစ်ရသေးတဲ့အချိန်မှာ method ခေါ်တာ မလုံခြုံလို့ compiler ကတားထားတာပါ။

Core Concept — Check ပြီးမှ သုံးမယ်

typeof လို JavaScript runtime check ကိုသုံးပြီး branch ခွဲလိုက်ပါ။ if block အတွင်း value ဟာ string ဖြစ်ကြောင်း compiler ကသိသွားပြီး string method တွေကို safe ဖြစ်အောင်သုံးနိုင်ပါတယ်။

မှတ်မိလွယ်တဲ့ ပုံစံ
  1. string | number
  2. typeof value === "string"
  3. string

Broad Type ကို runtime check ဖြင့်စစ်ပြီး လက်ရှိ branch အတွက် Narrowed Type ရလာပါတယ်။

General Pattern

typescript
if (typeof value === "string") {
  // value is string here
}

Condition က true ဖြစ်တဲ့ block အတွင်းမှာ value ကို string အဖြစ် narrow လုပ်ထားပါတယ်။

အသေးဆုံး အသုံးဝင်တဲ့ Example

typescript
function printValue(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase())
  } else {
    console.log(value.toFixed(2))
  }
}

printValue("hello")
printValue(12)

Code ကို တစ်ဆင့်ချင်း ဖတ်မယ်

  1. Line 1value: string | number

    Function က string သို့မဟုတ် number နှစ်မျိုးလုံးလက်ခံနိုင်ပါတယ်။

  2. Line 2typeof value === "string"

    Runtime မှာ value ဟာ string ဟုတ်မဟုတ် စစ်ပါတယ်။

  3. Line 3value.toUpperCase()

    ဒီ branch အတွင်း value ဟာ string လို့ TypeScript သိပြီးသားဖြစ်လို့ method ကို safe ဖြစ်အောင်ခေါ်နိုင်ပါတယ်။

  4. Lines 4–5else / value.toFixed(2)

    string မဟုတ်ရင် ကျန်တဲ့ဖြစ်နိုင်ခြေက number ပဲဖြစ်လို့ number method ကိုသုံးနိုင်ပါတယ်။

You should see
HELLO
12.00

Input Type တစ်မျိုးစီက ကိုက်ညီတဲ့ branch ကိုဝင်ပါတယ်။

Execution Flow
  1. value: string | number
  2. typeof value === "string"?

Yes

string → toUpperCase()

No

number → toFixed()

Narrowing Pattern တွေကို တဖြည်းဖြည်း တိုးမယ်

1. Truthiness Narrowing

if (value) က null, undefined, empty string, 0 စတဲ့ falsy values တွေကိုဖယ်ပေးနိုင်ပါတယ်။ ဒါပေမယ့် empty string က valid data ဖြစ်နိုင်ရင် တိတိကျကျစစ်ပါ။

typescript
function greet(name: string | null) {
  if (!name) return "Hello, guest"
  return `Hello, ${name}`
}

2. Equality Narrowing

=== စစ်ပြီး values နှစ်ခုတူတယ်ဆိုရင် နှစ်ဖက်စလုံးမှာ ထပ်တူဖြစ်နိုင်တဲ့ Type ကို compiler ကသိနိုင်ပါတယ်။

typescript
function compare(a: string | number, b: string | boolean) {
  if (a === b) {
    return a.toUpperCase() // both are string here
  }
  return "Different values"
}

3. in Operator

Object union တစ်ခုမှာ property ရှိ၊ မရှိစစ်ပြီး member ကိုခွဲချင်ရင် in operator ကအသုံးဝင်ပါတယ်။

typescript
type Admin = { name: string; permissions: string[] }
type Customer = { name: string; points: number }

function openDashboard(user: Admin | Customer) {
  if ("permissions" in user) {
    return `Admin tools: ${user.permissions.length}`
  }
  return `Reward points: ${user.points}`
}

4. instanceof Narrowing

Date, Error သို့ class instance လို prototype chain ရှိတဲ့ value တွေကို instanceof နဲ့စစ်နိုင်ပါတယ်။ Interface က runtime မှာမရှိတဲ့အတွက် instanceof Interface လို့မစစ်နိုင်ပါဘူး။

typescript
function formatDate(value: Date | string) {
  if (value instanceof Date) {
    return value.toISOString()
  }
  return new Date(value).toISOString()
}

5. Custom Type Guard

Complex object check ကို function တစ်ခုအဖြစ်ပြန်သုံးချင်ရင် value is User ဆိုတဲ့ type predicate ကို return type မှာရေးနိုင်ပါတယ်။ Boolean true ဖြစ်တာနဲ့ compiler က value ကို User အဖြစ် narrow လုပ်ပေးပါတယ်။

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"
}

function welcome(value: unknown) {
  return isUser(value) ? `Welcome ${value.name}` : "Invalid user"
}

6. Discriminated Unions

Union member တစ်ခုစီမှာ status လို shared literal field ထားပါ။ status ကိုစစ်လိုက်တာနဲ့ branch တစ်ခုလုံးကိုတိကျစွာ narrow လုပ်နိုင်ပါတယ်။

typescript
type ApiResult =
  | { status: "success"; data: User[] }
  | { status: "error"; message: string }

function renderResult(result: ApiResult) {
  if (result.status === "success") {
    return `Found ${result.data.length} users`
  }
  return `Error: ${result.message}`
}

7. Exhaustive Checking

Union variant အသစ်ထည့်တဲ့အခါ မကိုင်တွယ်ရသေးတဲ့ branch ကို compile-time မှာသိချင်ရင် never နဲ့ exhaustive check လုပ်ပါ။

typescript
function assertNever(value: never): never {
  throw new Error(`Unhandled value: ${JSON.stringify(value)}`)
}

function render(result: ApiResult): string {
  switch (result.status) {
    case "success": return `${result.data.length} users`
    case "error": return result.message
    default: return assertNever(result)
  }
}

Production usage

Real Project — API data ကို boundary မှာစစ်မယ်

fetch().json() ကရလာတဲ့ data ကို TypeScript type annotation တပ်လိုက်ရုံနဲ့ runtime မှာမှန်သွားတာမဟုတ်ပါဘူး။ External data ကို unknown အဖြစ်လက်ခံပြီး validation ဖြတ်ပြီးမှ app အတွင်းကိုပေးပါ။

typescript
async function loadUser(): Promise<User> {
  const response = await fetch("/api/user")
  const data: unknown = await response.json()

  if (!isUser(data)) {
    throw new Error("Invalid user response")
  }

  return data // data is User here
}
You should see
Valid data  → User အဖြစ် return
Invalid data → Error throw

Type Guard က untrusted boundary ကို app ရဲ့ trusted contract အဖြစ်ပြောင်းပေးပါတယ်။

Common Mistake — any နဲ့ safety ကိုပိတ်မထားပါနဲ့

any သုံးလိုက်ရင် compiler က property နဲ့ method တွေကိုမစစ်တော့ပါဘူး။ unknown ကတော့ အသုံးမပြုခင် narrow လုပ်ခိုင်းတဲ့အတွက် external data အတွက်ပိုလုံခြုံပါတယ်။

မကောင်းတဲ့ ပုံစံ

typescript
function print(value: any) {
  value.toUpperCase() // compiles, but may crash
}

ပိုကောင်းတဲ့ ပုံစံ

typescript
function print(value: unknown) {
  if (typeof value === "string") {
    console.log(value.toUpperCase())
  }
}

Best Practice

  • External input ကို unknown မှစပြီး boundary မှာ validate လုပ်ပါ။
  • တစ်ခုတည်းသော literal discriminant field ကိုသုံးပါ။
  • as assertion မသုံးခင် runtime check သို့ contract ပြင်နိုင်မလား စဉ်းစားပါ။
  • Union အားလုံးကိုကိုင်တွယ်ရမယ်ဆိုရင် never exhaustive check ထည့်ပါ။

ကိုယ်တိုင်စမ်းကြည့်ပါ

double() ကို ပြည့်စုံအောင်ရေးပါ။ number ဆိုရင် 2 နဲ့မြှောက်ပြီး string ဆိုရင် နှစ်ကြိမ်ဆက်ပေးရပါမယ်။ Run နဲ့စမ်းကြည့်ပါ။

typescript
function double(value: number | string) {
  // Write your narrowing here
}

console.log(double(4))
console.log(double("Hi"))

အလုပ်ဖြစ်ကြောင်း ဒီလိုသိမယ်: 8 / HiHi

Mini challenge

getUserDisplayName()

User | Guest union ကို Type Guard ဖြင့်ခွဲပြီး မှန်ကန်တဲ့ display name ပြန်ပေးတဲ့ function ရေးပါ။

  • User ဆိုရင် name ကိုပြန်ပေးပါ။
  • Guest ဆိုရင် Guest: <id> ပုံစံပြန်ပေးပါ။
  • any နဲ့ type assertion မသုံးပါနှင့်။
typescript
type User = { kind: "user"; name: string }
type Guest = { kind: "guest"; id: number }

function getUserDisplayName(person: User | Guest) {
  // Your code
}

ရလဒ်: User နဲ့ Guest နှစ်မျိုးလုံးအတွက် display name မှန်ရမယ်။

အရိပ်အမြွက် ကြည့်ရန်

kind field ကိုစစ်ပါ။ ဒါက discriminated union ဖြစ်ပါတယ်။

အဖြေ ကြည့်ရန်
typescript
function getUserDisplayName(person: User | Guest) {
  if (person.kind === "user") return person.name
  return `Guest: ${person.id}`
}

Quick Quiz 1 / 3

typeof value === "string" က ဘာလုပ်တာလဲ။

Quick Quiz 2 / 3

Untrusted API data အတွက် ဘယ် Type နဲ့စသင့်သလဲ။

Quick Quiz 3 / 3

never exhaustive check ရဲ့ အဓိကအကျိုးကျေးဇူးက ဘာလဲ။

ဒီသင်ခန်းစာမှာ

  • Broad Type ကို runtime check ဖြင့် narrow လုပ်တတ်ပြီ။
  • typeof, truthiness, equality, in နဲ့ instanceof ကို သင့်တော်တဲ့နေရာမှာရွေးသုံးတတ်ပြီ။
  • Custom Type Guard နဲ့ untrusted data ကိုစစ်တတ်ပြီ။
  • Discriminated union နဲ့ never exhaustive checking ကိုနားလည်ပြီ။
  • any ထက် unknown ကို safe boundary အဖြစ်သုံးသင့်ကြောင်းသိပြီ။

TypeScript Handbook — Narrowing — TypeScript

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Type Narrowing and Type Guards | Thuta Learning