函数

2022/9/26 TypeScript

# 写法

# 命名函数

函数中x和y参数都是string类型,小括号后面的string代表的是该函数的返回值也是string类型

function add(x:string,y:string):string{
  return x+y
}
const result:string=add('路飞','索隆')
console.log(result)

# 匿名函数

const result=function add(x:string,y:string):string{
  return x+y
}
console.log(result('路飞','索隆'))

# 完整写法

const result:(x:string,y:string)=>number=function(x:number,y:number):number{
  return x+y
}
console.log(result(10,100))

# 可选参数和默认参数

可选参数:函数在声明时候,内部的阐述使用?进行修饰,表示这个参数可传可不传 默认参数:函数在声明的时候,函数内部参数具有默认值,此时这个参数叫做默认参数

  const fullName=function(firstName:string='罗罗诺亚',lastName?:lastName):string{
    if(lastName){
      return fistName+"-"+lastName
    }else{
      return fistName
    }
  }

# 剩余参数

剩余参数是放在函数声明的时候所有参数的最后

function add(str:string,str2:string,...args:string[]){
  console.log(str)
  console.log(str2)
  console.log(args)
}
add('1','2','3','4','5')

# 函数重载

函数名字相同,参数的类型或者个数不同

// 函数重载
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
  }
}
// 正确
add(1,1)
add('1','1')
// 错误
add('1',1)
add(1,'1')
Last Updated: 2022/9/26 16:30:33