- 封装
//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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。