1. 程式人生 > >Typescript常見三種函式型別

Typescript常見三種函式型別

Typescript有常見三種函式型別:

  1. 分別是普通的函式;
  2. 有可選引數的函式;
  3. 有剩餘引數的函式;

普通函式

function findMan(age:number):string{
  return 'find the '+ age + 'years'
}

有可選引數的函式

function findPeople(age:number,name?:string):string{
  if(name){
    return 'find the '+ age + 'years and name is'+ name;
  }else{
    return 'find the '+ age +'and no name!';
  }
}

有剩餘引數的函式

function findRest(age:number,...xuqiu:string[]):string{
  let yy = "";
  for(let i=0; i< xuqiu.length;i++){
     yy = yy + xuqiu[i];
     if(i < xuqiu.length -1){
          yy = yy +'、'
     }
  }
  return '需求有:'+yy;
}

在這裡檢視列印結果:

var age:number = 18;
var result:string = findMan(age);
var resule2:string = findPeople(22,"HaoRen");
var resule3:string = findRest(22,'美女','人妖','SM','SB');

console.log(result);
console.log(resule2);
console.log(resule3);