TypeScript函数
函数定义的两种方式:
1.
let log=function(message){
cosole.log(message);
}
let log2=(message:string)=>{ //可以给函数绑定它的类型,函数中的语句只有一句时,{}可以省略
cosole.log(message);
}
log2("hello"); //参数只能传递string类型
let log3=(message:string,code:number)=>{
cosole.log(message,code);
}
log3("hello",2); //到用这个函数时,必须传指定类型的两个参数
可选参数:
let log4=(message:string,code?:number)=>{
cosole.log(message,code);
}
log3("hello"); //code后面加入?(必须加在可选参数的末尾参数),调用时可省略此参数 ,code会被默认设定为undefined
默认参数:
let log5=(message:string,code:number=0)=>{
cosole.log(message,code);
}
log3("hello"); //再不输入code的值的情况下,默认code=0
log3("hello",2); //当输入了新数据会覆盖默认值
可变参数:
function peopleName(firstName:string,...restOfname:string[]){ //调用时可输入多个参数
return firstName+""+restOfname.join(" ");
}
Lambads与this关键字的使用
举例:
let people={ //随机获取一个name
name:["iwen","ime","if","bean"],
getName:function(){
return()=>{ //引入lambans
let i=Math.floor(Math.random()+4);
return{
n:this.name[i]; //使用Lambans后可以调用this.name
}
}
}
}
重载
举例:
function attr(name:string):string;
function attr(age:number):number;
function attr(nameorage:any){
if(nameorage&&typeof nameorage==="string"){
alert("姓名");
}
else{
alert("年龄");
}
}
attr("Hello");
attr(10);