Skip to content
GitHub

Keys, Values များနှင့် အလုပ်လုပ်ခြင်း: Record<K, T>

Record<K, T>: Key နဲ့ Value Type တွေပါတဲ့ Object ပုံစံများ သတ်မှတ်ခြင်း

Section titled “Record<K, T>: Key နဲ့ Value Type တွေပါတဲ့ Object ပုံစံများ သတ်မှတ်ခြင်း”
  • ဘာလုပ်ပေးလဲ: Record<K, T> က Object Type တစ်ခုကို လုပ်ပေးတယ်။ အဲဒီ Object ရဲ့ Property Key တွေဟာ K Type ဖြစ်ရမယ်။ Property Value တွေက T Type ဖြစ်ရမယ်။
    • K (Key) က အများအားဖြင့် string, number, symbol ဒါမှမဟုတ် သီးခြား string / number နာမည်လေးတွေရဲ့ ပေါင်းစပ်မှု (union) ဖြစ်တတ်တယ်။
    • T (Value) ကတော့ အဲဒီ Key တွေနဲ့ သက်ဆိုင်တဲ့ တန်ဖိုးတွေရဲ့ Type ဖြစ်တယ်။
  • ဘယ်လို သုံးမလဲ:
    1. Feature Flags (အဖွင့်အပိတ်များ):
      • Feature Flag တွေက Program ရဲ့ လုပ်ဆောင်ချက် အချို့ကို ဖွင့်/ပိတ် လုပ်နိုင်အောင် ထိန်းချုပ်ဖို့ သုံးတဲ့ Object တွေပဲ။ Key က Feature နာမည်၊ Value က true (ဖွင့်) / false (ပိတ်) ဖြစ်မယ်။
index.ts
// FeatureFlags ဆိုတဲ့ Type အသစ် လုပ်မယ်။ Key တွေက string နာမည်တွေ၊ Value တွေက boolean ဖြစ်ရမယ်။
type FeatureFlags = Record<"newUserProfilePage" | "darkMode" | "betaFeatureX", boolean>;
const currentFlags: FeatureFlags = {
newUserProfilePage: true,
darkMode: false,
betaFeatureX: true,
// anotherFlag: true; // Error ပြလိမ့်မယ်။ 'anotherFlag' က FeatureFlags ထဲမှာ မရှိဘူး။
};
  1. Simple Dictionary/Cache (ရိုးရှင်းသော အဘိဓာန်/မှတ်ဉာဏ်):
    • Data တွေကို Key-Value ပုံစံနဲ့ သိမ်းထားတဲ့ Dictionary ဒါမှမဟုတ် Cache မျိုးတွေ လုပ်တဲ့အခါ သုံးနိုင်တယ်။ ဥပမာ User ID ကို Key အဖြစ်၊ User Profile ကို Value အဖြစ် သိမ်းတာမျိုး။
index.ts
// UserCache ဆိုတဲ့ Type အသစ် လုပ်မယ်။ Key တွေက string (user ID) ဖြစ်မယ်။ Value တွေက UserProfile ဖြစ်ရမယ်။
type UserCache = Record<string, UserProfile>;
const cache: UserCache = {
"user-123": { id: 123, username: "cachedUser", bio: null, isActive: true, lastLogin: new Date() },
"user-456": { id: 456, username: "anotherCached", email: "c@ex.com", bio: "Bio here", isActive: false, lastLogin: new Date() }
};
  1. CSS-in-JS Style Objects (CSS ပုံစံ Object များ):
    • JavaScript ထဲမှာ CSS (Cascading Style Sheets) ရဲ့ ပုံစံတွေ သတ်မှတ်တဲ့ Object တွေ လုပ်တဲ့အခါ သုံးနိုင်တယ်။ Key က CSS Property နာမည် (string)၊ Value က CSS တန်ဖိုး (string ဒါမှမဟုတ် number) ဖြစ်မယ်။
index.ts
// CSSProperties ဆိုတဲ့ Type အသစ် လုပ်မယ်။ Key တွေက string၊ Value တွေက string ဒါမှမဟုတ် number ဖြစ်ရမယ်။
type CSSProperties = Record<string, string | number>;
const styles: CSSProperties = {
padding: "10px", // Key က string၊ Value က string
marginTop: 20, // Key က string၊ Value က number
color: "blue", // Key က string၊ Value က string
// borderRadius: true // Error ပြလိမ့်မယ်။ Value က boolean ဖြစ်နေတယ်။ string ဒါမှမဟုတ် number ဖြစ်ရမယ်။
};