关于javascript:TypeScript函数

  • 封装
//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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理