Callbacks နှင့် Function Signatures

7.0.2

Value အဖြစ် ပေးလိုက်တဲ့ function တွေအတွက် type ရေးပါ။ ခေါ်တဲ့ဘက်က ဘယ် arguments တွေ ပေးရမလဲ ပြတ်ပြတ်သားသား သတ်မှတ်ပါ။

ဒီစာမျက်နှာမှာ

Callback Type သတ်မှတ်ခြင်း

Callback ရဲ့ parameters နဲ့ return value ကို function type နဲ့ ဖော်ပြပါ။ ခေါ်တဲ့ဘက်က implement ပုံ မတူပေမယ့် contract တစ်မျိုးတည်း သုံးနိုင်ပါတယ်။

type PriceRule = (price: number) => number;

function applyRule(price: number, rule: PriceRule): number {
  return rule(price);
}

const salePrice = applyRule(5, amount => amount * 0.8);

Optional သို့ Default Parameter ရွေးခြင်း

Parameter မှာ ? ပါရင် ခေါ်တဲ့အခါ ချန်ထားနိုင်လို့ function ထဲမှာ undefined ကို ကိုင်တွယ်ပါ။ Argument ချန်ထားရင် သို့ undefined ပေးရင် default သုံးပါတယ်။ Union parameter နဲ့ ဆက်စပ်မှု ရှင်းရှင်း မဖော်ပြနိုင်တဲ့အခါ overload သုံးပါ။

function greet(name: string, title?: string): string {
  return title ? `Hello, ${title} ${name}!` : `Hello, ${name}!`;
}

function formatPrice(amount: number, currency = "USD"): string {
  return `${amount} ${currency}`;
}

console.log(greet("Taylor"));             // Hello, Taylor!
console.log(greet("Taylor", "Dr."));      // Hello, Dr. Taylor!
console.log(formatPrice(12));            // 12 USD
console.log(formatPrice(12, "EUR"));     // 12 EUR

တရားဝင် ကိုးကားချက်များ