Type Annotation(:) နဲ့ Type Assertion (as) ရဲ့ ပြဿနာ
Type Annotation (:) ကြောင့် ဖြစ်တဲ့ ပြဿနာ - Type ကျယ်ပြန့်သွားခြင်း (The Widening Effect)
Section titled “Type Annotation (:) ကြောင့် ဖြစ်တဲ့ ပြဿနာ - Type ကျယ်ပြန့်သွားခြင်း (The Widening Effect)”ပြီးခဲ့တဲ့ သင်ခန်းစာက ဖန်တီးခဲ့တဲ့ myAppConfig ဟာ AppConfig Type အတိုင်း မှန်ကန်ကြောင်းကို Type Annotation (:) သုံးပြီး သေချာအောင် လုပ်ချင်ရင် ဘာဖြစ်သွားမလဲ ဆိုတာ ကြည့်ရအောင်။
// AppConfig ဆိုတဲ့ Type ဖြစ်ကြောင်း Annotation (:) သုံးပြီး သတ်မှတ်လိုက်တယ်။const annotatedConfig: AppConfig = { env: "development", port: 3000, featureFlags: { darkMode: true, newOnboarding: false }};ဒီလို annotatedConfig: AppConfig လို့ ရေးပြီး Type ကပ်ပေးလိုက်တာနဲ့ TypeScript က annotatedConfig အကြောင်း ဘာတွေ ပြောင်းလဲ သိရှိသွားသလဲ ဆိုတာကို လေ့လာကြည့်ရအောင်။
annotatedConfig.env: သူ့ရဲ့ Type ဟာ ယခင်က"development"အတိအကျ ဖြစ်နေရာကနေ၊ အခုတော့"development" | "production" | "test"ဆိုပြီး Union Type ကြီး ဖြစ်သွားပါပြီ။- အရေးကြီးတဲ့ အချက်က
"development"လို့ အတိအကျ သိထားခဲ့တဲ့ အသေးစိတ် အချက်အလက်လေး ပျောက်ဆုံးသွားတာပါ။ TypeScript က “ဒီenvက ၃ ခုထဲက တစ်ခုခုတော့ ဖြစ်နိုင်တယ်။ ဒါပေမဲ့ ဘယ်တစ်ခုလဲ ဆိုတာကိုတော့ အတိအကျ မသိတော့ဘူး” လို့ မှတ်ယူသွားပါတယ်။
- အရေးကြီးတဲ့ အချက်က
annotatedConfig.featureFlags: သူ့ရဲ့ Type ဟာRecord<string, boolean>အဖြစ် ပြောင်းလဲသွားပါတယ်။- ဒီနေရာမှာလည်း ပြဿနာက
darkModeနဲ့newOnboardingဆိုတဲ့ သီးခြား Keys တွေ ပါဝင်တယ်ဆိုတဲ့ အချက်ကို TypeScript က မသိတော့ပါဘူး။ သူက “ဒီအထဲမှာ Key က စာသား (string) ဖြစ်ရမယ်၊ Value က true/false ဖြစ်ရမယ်” လို့ ယေဘုယျလောက်သာ မှတ်သားထားပါတော့တယ်။
- ဒီနေရာမှာလည်း ပြဿနာက
အဓိက ပြဿနာ (The Crux)
Section titled “အဓိက ပြဿနာ (The Crux)”ဒီလို ဖြစ်သွားတဲ့အတွက် ကျွန်တော်တို့က annotatedConfig.featureFlags.darkMode လိုမျိုး အတိအကျ ရှိနေတဲ့ Property ကို Access လုပ်ဖို့ ကြိုးစားတဲ့အခါ -
// console.log(annotatedConfig.featureFlags.darkMode);// ^^^^ Error ပြပါလိမ့်မယ်: Property 'darkMode' does not exist on type 'Record<string, boolean>'.
// အကြောင်းရင်းကတော့ TypeScript က 'featureFlags' ဟာ ယေဘုယျအားဖြင့် (Record<string, boolean>) string key ကနေ boolean value ပြန်ပေးနိုင်တဲ့ Object တစ်ခုလို့ပဲ သိသွားလို့ပါ။// 'darkMode' ဆိုတဲ့ သီးခြား Key အတိအကျ ပါဝင်နေတယ် ဆိုတာကို မမှတ်မိတော့ပါဘူး။တစ်စိတ်တစ်ပိုင်း ဖြေရှင်းနည်း: as const
Section titled “တစ်စိတ်တစ်ပိုင်း ဖြေရှင်းနည်း: as const”ဒီပြဿနာကို ယာယီ ဖြေရှင်းဖို့အတွက် as const (Type Assertion ရဲ့ ပုံစံကွဲ) ကို အသုံးပြုလို့ ရပါတယ်။
const constConfig = { env: "development", port: 3000, featureFlags: { darkMode: true, newOnboarding: false }} as const; // ဒီ Object တစ်ခုလုံးကို 'as const' (ပြောင်းလဲလို့ မရတဲ့ အရာ) လို့ သတ်မှတ်လိုက်တယ်။
// ဒါဆိုရင် TypeScript က constConfig အကြောင်းကို အောက်ပါအတိုင်း အသေးစိတ် အတိအကျ သိသွားပါမယ်:// {// readonly env: "development"; // 'development' လို့ အတိအကျ သိတယ်။ Readonly ဖြစ်လို့ ပြင်လို့မရဘူး။// readonly port: 3000; // 3000 လို့ အတိအကျ သိတယ်။// readonly featureFlags: {// readonly darkMode: true; // 'darkMode' ပါတယ်လို့ အတိအကျ သိတယ်။// readonly newOnboarding: false; // 'newOnboarding' ပါတယ်လို့ အတိအကျ သိတယ်။// };// }