1. Default Parameters
Passing in a value will override the default parameter, and it is fine to pass no value.
function getinfo(name:string,age:number=20):string{
return `${name}---${age}`
}
console.log(getinfo("TOM")); // TOM 20
console.log(getinfo("TOM",30)); // TOM 30
2. Optional parameters
Optional values may or may not be passed, but the optional parameters must be placed at the end of the parameter list.
function getinfo1(name:string,age?:number):string{
if(age){
return `${name}---${age}`
}else{
return `${name}---Age confidentiality`
}
}
console.log(getinfo1("TOM")); // TOM Age confidentiality
console.log(getinfo1("TOM",30)); // TOM 30
3. Remaining parameters
Let’s start with a basic application.
function sum(a:number,b:number,c:number,d:number):number{
return a+b+c+d;
}
console.log(sum(1,2,3,4)); // 10
The above code can then be rewritten in the form of remaining arguments, using es6’s three-point operator (equivalent to assigning arguments to an array and then traversing that array with a loop).
function sum1(...result:number[]):number{
var sum=0;
for(let i=0;i<result.length;i++){
sum+=result[i];
}
return sum;
}
console.log(sum1(1,2,3,4,5)); // 15
console.log(sum1(1,2,3,4,5,6)); // 21
Or in this case, the first parameter you pass in is assigned to a, and the rest is put into an array.
function sum1(a:number,...result:number[]):number{
var sum=a;
for(let i=0;i<result.length;i++){
sum+=result[i];
}
return sum;
}
console.log(sum1(1,2,3,4,5));//15
console.log(sum1(1,2,3,4,5,6));//21
4. Arrow Functions
// es5 normal writing method
setTimeout(function(){
alert("run");
},3000)
// writing the es6 arrow function
setTimeout(()=>{
alert("run");
},3000)