Skip to content
GitHub

Generic Function ကို သုံးပုံ: တိုက်ရိုက်ပြောပြခြင်း နဲ့ သူဘာသာသိခြင်း (Inference)

ဒီလိုမျိုး Generic အသုံးပြုပြီး ရေးထားတဲ့ Function တွေကို ဘယ်လို ခေါ်သုံးရမလဲ? အဓိက နည်းလမ်း (၂) ခု ရှိပါတယ်။

နည်းလမ်း (၁): Type ကို ကိုယ်တိုင် တိုက်ရိုက် ပြောပြခြင်း

Section titled “နည်းလမ်း (၁): Type ကို ကိုယ်တိုင် တိုက်ရိုက် ပြောပြခြင်း”

Function ကို ခေါ်သုံးတဲ့အခါ Angle Bracket < > တွေကြားထဲမှာ T နေရာအတွက် ဘယ်လို Type မျိုး ဖြစ်ရမယ်ဆိုတာကို ကျွန်တော်တို့ ကိုယ်တိုင် တိုက်ရိုက် သတ်မှတ် ထည့်သွင်းပေးလို့ ရပါတယ်။

index.ts
// T နေရာမှာ string ဖြစ်ရမယ်လို့ ကိုယ်တိုင် တိုက်ရိုက် ပြောလိုက်တာ
let outputString = identity<string>("Hello Generics!");
// T နေရာမှာ number ဖြစ်ရမယ်လို့ ကိုယ်တိုင် ပြောလိုက်တာ
let outputNumber = identity<number>(123);
// T နေရာမှာ User Type ဖြစ်ရမယ်လို့ ကိုယ်တိုင် ပြောလိုက်တာ
interface User { name: string; }
let outputUser = identity<User>({ name: "Alice" });
console.log(outputString.toUpperCase()); // Type က string မှန်း သိလို့ toUpperCase() ကို ရဲရဲဝံ့ဝံ့ ခေါ်လို့ရတယ်၊ TypeScript က စစ်ပေးထားတယ်!
console.log(outputNumber.toFixed(2)); // Type က number မှန်း သိလို့ toFixed(2) ကို စိတ်ချလက်ချ ခေါ်လို့ရတယ်!
console.log(outputUser.name); // Type က User မှန်း သိလို့ .name ကို သုံးလို့ရတယ်!

နည်းလမ်း (၂): Type Inference (TypeScript က သူ့ဘာသာ ခန့်မှန်းသိခြင်း)

Section titled “နည်းလမ်း (၂): Type Inference (TypeScript က သူ့ဘာသာ ခန့်မှန်းသိခြင်း)”

လက်တွေ့မှာ အချိန်အများစုအတွက်တော့ TypeScript ဟာ ကျွန်တော်တို့ ထည့်လိုက်တဲ့ Data တန်ဖိုးကို ကြည့်ပြီး T နေရာမှာ ဘယ် Type မျိုး ဖြစ်သင့်သလဲ ဆိုတာကို သူ့ဘာသာသူ အလိုအလျောက် ခန့်မှန်း သိရှိနိုင်ပါတယ်။ ဒီလိုမျိုး TypeScript က ကိုယ်တိုင် ခန့်မှန်းပေးတာကို Type Inference လို့ ခေါ်ပါတယ်။ ဒီနည်းလမ်းက Code ရေးရတာကို ပိုမြန်ဆန်စေပြီး ပိုလွယ်ကူစေပါတယ်။

index.ts
// "Hello Inference!" ဆိုတဲ့ string ကို ထည့်လိုက်တာနဲ့ T က string လို့ TypeScript က သူ့ဘာသာ ခန့်မှန်းသိတယ်
let inferredString = identity("Hello Inference!");
// 456 ဆိုတဲ့ number ကို ထည့်လိုက်တာနဲ့ T က number လို့ ခန့်မှန်းသိတယ်
let inferredNumber = identity(456);
// { name: "Bob" } ဆိုတဲ့ object ကို ထည့်လိုက်တာနဲ့ T က { name: string } ပုံစံလို့ ခန့်မှန်းသိတယ်
let inferredUser = identity({ name: "Bob" });
console.log(inferredString.toUpperCase()); // ခန့်မှန်းသိပေမယ့်လည်း Type က မှန်ကန်နေလို့ စိတ်ချရတုန်းပဲ!
console.log(inferredNumber.toFixed(2));
console.log(inferredUser.name);