- 封装
//js中的函数封装形式function add1(x,y){ return x+y}const add2 = function(x,y){ return x+y}//TS中的函数封装,能够指定参数和返回值的类型function add3(x:number,y:number):number{ return x+y}const add4 = function(x:number,y:number):number{ return x+y]//函数的残缺写法 //const add5:类型 = function(x:number,y:number):number{return x+y} //类型=(x:number,y:number)=>numberconst add5: (x:number,y:number)=>number =function(x:number,y:number):number{ return x+y}
可选参数和默认参数
在TS中,调用函数时,传入参数的数量与类型与定义函数时设定的形参不统一会提醒谬误,咱们能够在定义函数时给参数设置默认值,也能够设置参数为可选参数(调用时可传,可不传)默认参数: 形参名:类型 = 默认值可选参数: 形参名?:类型
function getFullName(firstName:string='张三',lastName?:string):string{ if(lastName){ return firstName + '_' + lastName }else{ return firstName }}console.log(getFullName()) //张三console.log(getFullName('诸葛')) //诸葛console.log(getFullName('诸葛','孔明')) //诸葛_孔明
残余参数(rest参数)
...args:string[] //每个元素都是string类型的数组
function showMsg(str:string,...args:string[]){ //args是形参名,可用其余的名,但默认用args consoel.log(str) //a console.log(args) //['b','c','d','e']}showMsg('a','b','c','d','e')
- 函数重载
函数名字雷同,依据函数的参数及个数不同,执行不同操作
//申明函数重载function add(x:string,y:string):stringfunction add(x:number,y:number):number//申明函数function add(x:string|number,y:string|number):string|number{ if(typeof x === 'string'&& typeof y === 'string'){ return x+'_'+y }else if(typeof x === 'number'&& typeof y === 'number') { return x+y }}console.log(add('诸葛','孔明')) //诸葛_孔明console.log(add(10,10)) //20console.log(add('a',1)) //提醒谬误 持续编译打印undefinedconsole.log(add(2,'b')) //提醒谬误 持续编译打印undefined