TS之函數及函數傳參


以實例的形式展示

1.ts定義函數

//1 普通用法
function run(): string {
  return 'run';
}

// function run1(): string {
//   return 111;  //報錯
// }

//2 匿名函數方式
let fun1 = function (): number {
  return 123;
}
console.log(fun1());

 

 2.函數傳參

(1)傳遞等量參數

function getInfo(uname: string, age: number): string {
  return `${uname}---${age}`;
}
console.log(getInfo('lisi', 12));

 

 (2)可選參數 (使用?)

// 可選參數
function getInfo(uname: string, age?: number): string {
  if (age) {
    return `${uname}---${age}`;
  } else {
    return `${uname}---年齡保密`
  }
}
console.log(getInfo('lisi', 12));
console.log(getInfo('lisi'));

 

(3)默認參數

function getInfo(uname: string, age: number = 20): string {
  if (age) {
    return `${uname}---${age}`;
  } else {
    return `${uname}---年齡保密`
  }
}
console.log(getInfo('lisi'));
console.log(getInfo('lisi',30));

(4)剩余參數

  ①普通寫法

function sum(a: number, b: number, c: number, d: number): number {
  return a + b + c + d;
}
console.log(sum(1, 2, 3, 4));

 

  ②三點運算符

function sum1(...res: number[]): number {
  return res.reduce((p, e, i, a) => {
    return p + e;
  }, 0)
}
console.log(sum1(1, 2, 3, 4, 5));

 

(5)函數重載

js的函數重載,是通過為同一函數提供多個函數類型定義來實現多種功能的目的

function getInfo(nam: string): string;
function getInfo(age: number): number;
function getInfo(str: any): any {
  if (typeof str === 'string') {
    return `我叫:` + str;
  } else {
    return `年齡:` + str;
  }
};

console.log(getInfo('張三'));
console.log(getInfo(25));
console.log(getInfo(錯誤));  //錯誤

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM