Function
Similar to JavaScript functions
Have some additional features...
types
default parameters
rest parameters
lambdas
function greet(){
alert("Hello world.");
}
Function Types
Functions can have types
Types describe what is returned by a function
function getCountry() : string {
return "Canada";
}
var c : string = getCountry(); // ok
var c : number = getCountry(); // compile-time error
Optional Parameters
function sayHappyBirthday(name?: string){
console.log("Happy Birthday " + name);
}
sayHappyBirthday(); // OK
sayHappyBirthday("Hemant"); // OK
Default Parameters
function sayHappyBirthday(name?: string = "Buddy!"){
console.log("Happy Birthday " + name);
}
sayHappyBirthday(); // Happy Birthday Buddy!
sayHappyBirthday("Hemant"); // Happy Birthday Hemant
Rest Parameters
In JavaScript list of all arguments are provided in the mysterious arguments variable
it's real array ( so we can use array methods push, pop etc on it unlike arguments )
function roleCall(master: string, ...names : string[]){
console.log("Master is "+ master); // Master is Hemant
console.log(names); // ["Rickon", "Sansa", "Robb", "Arya"]
};
roleCall("Hemant","Varun","Vinay","Sasis","Arya");
Lambdas ( arrow function )
A different kind of function invocation where the value of this is not changed
Works similar to function but has a preferable syntax
Also known as an arrow or a fat arrow function
var superhero = {
name: "Hemant",
greet: function() {
setTimeout(() => {
console.log(this.name); // Hemant
}, 500);
}
};
superhero.greet();
Last updated
Was this helpful?