TypeScript Annotation vs Inference
Last updated
Last updated
Annotation vs Inference ကို အလွယ်ရှင်းပြရရင်
Type Annotation 👉 Type ကို manually သတ်မှတ် ခြင်း
Type Inference 👉 Type ကို TypeScript က auto ယူဆခြင်း
တို့ပဲ ဖြစ်ပါတယ် ။
အခြေခံအရ ( : ) column ကိုအသုံးပြုပြီး အနောက်မှာ type ကိုသတ်မှတ်ပါတယ် ။
Type ကို manually သတ်မှတ်ခြင်း code ကို လေ့လာကြည့်ကြပါမယ် ။
Programmer က Type ကို ကိုယ်တိုင်စီမံရေးသားတာ ဖြစ်ပါတယ် myName
variable ထဲကို string Type ပဲထည့်ပါမယ်လို့ ကြေငြာထားတာဖြစ်ပါတယ် ။ age
ထဲကို number Type ဖြစ်ပြီး ၊ isStudent
ထဲမှာ boolean Type အဖြစ်နဲ့ သုံးထားပါတယ် ။
Type Annotation က variable
, function parameter
, return type
, class property
တွေမှာ သတ်မှတ်နိုင်ပါတယ် ။ နောက်ပိုင်းအခန်းတွေမှာ ဆက်ပြီး လေ့လာ အသုံးပြုသွားမှာပါ ။
TypeScript က သင့်တော်တဲ့ Type ကို အလိုအလျှောက် အသုံးပြုပေးတာကို Inference လို့ခေါ်ပါတယ် ။
Type ကို ကိုယ်တိုင် (Manual) သတ်မှတ် ပေးစရာမလိုပါဘူး ။ age
variable ထဲကို တန်ဖိုး 25 ထည့်လိုက်တဲ့အခါ TypeScript က အလိုအလောက် number type ဖြစ်သတ်လို့ သတ်မှတ်ပေးလိုက်ပါတယ် ။
စာဖတ်သူက age
variable ကို Mouse နဲ့ ခဏကြာကြာလေး ငြိမ်ထားရင် သူ့ရဲ့ Type ကို မြင်နိုင်ပါတယ် ။
နောက်တစ်လိုင်းမှာ age = 'string';
string တန်ဖိုးထည့်လိုက်ရင် TypeScript server ကနေ Error Feedback ပြန်ပေးပါလိမ့်မယ် ။
ဒါဆို TypeScript ဘယ်လိုအလုပ်လုပ်သလဲ Inference နဲ့ Annotation ဆိုတာဘာလဲ အခြေခံအားဖြင့် သိသွားပါပြီ ။
ပုံမှန်အားဖြင့် Primitive Data Type တွေကိုသုံးတဲ့အခါ Inference (အလိုအလျောက် သတ်မှတ်ပေးခြင်း) ကိုသုံးလေ့ရှိပါတယ် ။
Primitive Types (7 မျိုး) - string
, number
, boolean
, bigint
, symbol
, null
, undefined
တို့ဖြစ်ပါတယ် ။
အခြား Complex ဖြစ်တဲ့ Object Type တွေကိုတော့ Annotation သုံးလေ့ရှိကြပါတယ်