Functions

Basic Function (string )

// function funname(parameter: type): return type hinting{ return; }
function city(val:string):string{
    return `Hello ${val}`;
}
console.log(city("Yangon"));
// output : Hello Yangon

Basic function (number addition)

function cal(num1:number, num2:number):number{
    return num1+num2;
}
console.log(cal(100, 200));
// output : 300

Basic Function (Car Price Calculator)

function car(brand:string, qty:number, tax:number):number{
    let price:number = 0;
    if(brand === "toyota") price = 3000;
    if(brand === "mazda") price = 2000;
    if(brand === "suzuki") price = 1000;

    let total:number = (price * qty) + tax;
    return total;
}

console.log(car("toyota", 1, 100)); // output : 3100
console.log(car("mazda", 2, 100)); // output : 4100

Arrow Function (Car Price Calculator)

let truck = (
    brand:string, 
    qty:number, 
    tax:number,
    discount:number // "noUnusedParameters": false
):number=>{
    let price:number = 0;
    if(brand === "toyota") price = 3000;
    if(brand === "mazda") price = 2000;
    if(brand === "suzuki") price = 1000;

    let total:number = (price * qty) + tax;
    return total;
}

console.log(truck("toyota", 1, 100, 10)); // 3100
console.log(truck("mazda", 2, 100, 10)); // 4100

tsconfig.json file တွင် "noUnusedParameters": false ဟု သတ်မှတ်ထားပါက parameter ကို code block တွင် ခေါ်မသုံးသော်လည်း error တက်မည်မဟုတ်ပါ။ "noUnusedParameters": true ဟုတ်သတ်မှတ်ထားပါက compile error ဖြစ်သွားမှာဖြစ်ပါတယ်။

Last updated