Object Types၊ Unions နှင့် Narrowing
7.0.2
Fields တွေ ဖော်ပြဖို့ object types၊ လက်ခံနိုင်တဲ့ ပုံစံတစ်ခုထက်ပိုရင် unions သုံးပါ။
Code စမ်းလို့ရတဲ့ သင်ခန်းစာ ဖွင့်ရန်
ဒီစာမျက်နှာမှာ
မဖြစ်မနေ ပါရမယ့် Fields နှင့် Optional Fields
Interface သို့ type alias နဲ့ object fields သတ်မှတ်နိုင်ပါတယ်။ Field နောက်က ? က optional ဖြစ်ပါတယ်။ Strict null checks နဲ့ဆို မရှိနိုင်တဲ့ value ကို string လို မသုံးခင် စစ်ပါ။
interface Product {
name: string;
price: number;
label?: string;
}
function displayName(product: Product) {
return product.label ?? product.name;
}
စစ်ဆေးပြီး Type ခွဲခြင်း
Union ကို typeof၊ equality သို့ literal value ပါတဲ့ shared field နဲ့ ခွဲနိုင်ပါတယ်။ ဥပမာမှာ ok စစ်တာနဲ့ branch တစ်ခုစီမှာ ဘယ် fields ရှိလဲ compiler က သိနိုင်ပါတယ်။
type Result =
| { ok: true; total: number }
| { ok: false; message: string };
function describe(result: Result) {
if (result.ok) return "Total: " + result.total;
return result.message;
}