Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingintermediate

Type Narrowing and Type Guards

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

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

  • Built-in type guards သုံးရန်
  • Discriminated union တည်ဆောက်ရန်
  • Exhaustive checking ရေးရန်

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

Type narrowing သည် runtime check အပေါ်မူတည်၍ TypeScript က broad type ကိုပိုတိကျသော type အဖြစ်သတ်မှတ်ခြင်းဖြစ်သည်။ Discriminated union တွင် shared literal field တစ်ခုထားခြင်းက branch တစ်ခုစီတွင်မှန်ကန်သော properties ကိုသာ access လုပ်နိုင်စေသည်။

typescript
type Result =
  | { status: 'success'; data: string[] }
  | { status: 'error'; message: string }

function render(result: Result): string {
  switch (result.status) {
    case 'success':
      return `Found ${result.data.length} items`
    case 'error':
      return `Error: ${result.message}`
  }
}

console.log(render({ status: 'success', data: ['Vue', 'TypeScript'] }))
You should see
Found 2 items

လက်တွေ့စမ်းကြည့်ရန်

Circle နှင့် Rectangle discriminated union တည်ဆောက်ပြီး shape တစ်မျိုးစီ၏ area ကိုတွက်သည့် function ရေးပါ။

TypeScript Handbook — NarrowingTypeScript

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

  • Type assertion ဖြင့် compiler ကိုအတင်းကျော်ခြင်း
  • Discriminant field ကို string အထွေထွေအဖြစ်သတ်မှတ်ခြင်း

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

Circle နှင့် Rectangle discriminated union တည်ဆောက်ပြီး shape တစ်မျိုးစီ၏ area ကိုတွက်သည့် function ရေးပါ။

You'll know it worked when: Found 2 items

Type Narrowing and Type Guards | Thuta Learning