//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)=>number const 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):string function 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)) //20 console.log(add('a',1)) //提示错误 继续编译打印undefined console.log(add(2,'b')) //提示错误 继续编译打印undefined