ရိုးရိုးလေး ရှင်းပြမယ်
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 — Narrowing — TypeScript