Functions in Type Script
There are four major things Type Script functions provide:
- Function signature type checks
- Optional and Default arguments
- Ellipsis arguments (...)
- Function Overloading
Function signature type checks
Type Script added syntactical sugar to the function definition. This will be very useful for compile time checking of the illegal values passed to the function.
function functionName (arg1 : type, arg2: type) : type {
// function body ...
}
If we see the example of adding numbers, we can re write JavaScript version as
function myFunction(arg1: number, arg2: number, arg3: number) : number {
return arg1 + arg2 + arg3
}
myFucntion(1,2,3) // returns 6
myFunction(1,2,"Naren") // TypeScript throws error about mismatching signatures
If we observe the syntax, it is like the one we saw while learning type section. Let us write a small program for converting Celsius to Fahrenheit.
// celsius_to_fahrenheit.ts
function CelToFaht(celsius: number) : number{
return (celsius * (9/5)) + 32;
}
console.log(CelToFaht(-50));
Now compile and run JS file
$ tsc celsius_to_fahrenheit.ts
$ node celsius_to_fahrenheit.js
-58
Optional and Default arguments
Programming languages like Python gives flexibility of passing arguments with optional arguments, keyword arguments. Similarly JavaScript programmers misuse the JavaScript's behavior of passing any number of arguments.
Optional arguments
Let us take a team entering a competition where at least one guy should present. All others are optional. Then we can define team as this.
function OnlyThreeOrLess( captain: string, vice_captain?: string,
member?: string) : string{
var members = captain +
(vice_captain != undefined)? vice_captain:"" +
(member != undefined)? member:"";
return members;
}
console.log(OnlyThreeOrLess("Naren"));
console.log(OnlyThreeOrLess("Naren", "Saikiran"));
// Error, too many params
console.log(OnlyThreeOrLess("Naren", "Saikiran", "Vivek", "Nivin"));
In the last statement, we tried to pass the more number of arguments and compiler throws error at such situations.
Default arguments
Default arguments are needed when we are expecting non-certain values into the function. In Type Script we can pass default arguments. Let us find the Regular compound interest for a bank.
Suppose that I had account in X bank and these are the parameters for calculating interest.
P = principal amount (initial investment)
r = annual interest rate (as a decimal)
n = number of times the interest is compounded per year
t = number of years
A = amount after time t
Suppose we have following default values set by bank X.
P = Variable Amount
r = 4.3%
n = 4 (Quarterly)
t = 5 years
A = ?
// compound_interest.ts
function RegularCompoundInterest(p:number, r:number= 0.043,
n:number = 4, t:number = 5): number {
return p * (Math.pow((1 + (r/n)), n * t));
}
console.log("$",RegularCompoundInterest(1000000));
$ tsc compound_interest.ts
$ node compound_interest.js
This is awesome. Only amount is passed and other arguments have default values. But what if those arguments are supplied to function. Suppose if we want to make span of deposit for 7 years instead of 5 then just pass undefined for other positional arguments and 7 years in place of last argument like this.
$ RegularCompoundInterest(1000000, undefined, undefined, 7);
Here even when Type Script sees the undefined in place of default value, it substitutes default value as the argument value. This is a provision for allowing developer to pass arguments correctly.
Ellipsis arguments (...)
This is similar to keyword arguments in Python. These are also called rest parameters. Sometimes we care the important arguments and dump remaining arguments blindly for some purpose. By example it will be clarified.
function displayImportantCities(capital: string,
...otherCities:string[]): string {
return capital + "," + otherCities.join(",");
}
console.log(displayImportantCities("New Delhi", "Hyderabad", "Mumbai", "Bengaluru"));
Here ellipsis(...) symbol is used to tell store all other arguments in the array with argument name.
Function overloading
The programmers who comes from the Object Oriented Design background easily remembers function over loading. It started with C++, and featured in many programming languages. Type Script allows you to have same function name for multiple functions with different signatures.
Let us program functions with same name called area but behavior changes with difference of arguments.
// Square
function area(length: number):number {
return length * length;
}
// Rectangle
function area(length: number, width: number):number {
return length * width;
}
console.log(area(6)); // 6
console.log(area(3, 4)); // 12
Function overloading is a powerful feature which enables us to create multiplexed behaviors with variation of argument signature.