函数返回值

  1. // 定义函数返回值
  2. function greet():string { // 返回一个字符串
  3. return "Hello World"
  4. }

函数参数

  1. function add(x: number, y: number): number {
  2. return x + y;
  3. }
  4. console.log(add(1,2))

参数是一个json对象:

  1. public async Login(userInfo: { userAccount:string, password:string, identification:string, rememberMe:string}) {
  2. let { userAccount, password,identification,rememberMe } = userInfo
  3. userAccount = userAccount.trim()
  4. await login({ userAccount, password,identification,rememberMe })
  5. setToken("LOGIN")
  6. this.SET_TOKEN("LOGIN")
  7. }

可选参数/默认参数/剩余参数

在 TypeScript 函数里,如果我们定义了参数,则我们必须传入这些参数,除非将这些参数设置为可选,可选参数使用问号标识 ?

  1. function buildName(firstName: string, lastName: string) {
  2. return firstName + " " + lastName;
  3. }
  4. let result1 = buildName("Bob"); // 错误,缺少参数
  5. let result2 = buildName("Bob", "Adams", "Sr."); // 错误,参数太多了
  6. let result3 = buildName("Bob", "Adams"); // 正确
  • 可选参数使用问号标识? ```typescript //可选参数使用问号标识? function buildName(firstName: string, lastName?: string) { if (lastName)
    1. return firstName + " " + lastName;
    else
    1. return firstName;
    }

let result1 = buildName(“Bob”); // 正确 let result2 = buildName(“Bob”, “Adams”, “Sr.”); // 错误,参数太多了 let result3 = buildName(“Bob”, “Adams”); // 正确

  1. - 默认参数
  2. ```typescript
  3. function calculate_discount(price:number,rate:number = 0.50) {
  4. var discount = price * rate;
  5. console.log("计算结果: ",discount);
  6. }
  7. calculate_discount(1000) // 正确
  8. calculate_discount(1000,0.30)// 正确
  • 剩余参数:当我们不知道要向函数传入多少个参数,这时候我们就可以使用剩余参数来定义 ```typescript function buildName(firstName: string, …restOfName: string[]) { return firstName + “ “ + restOfName.join(“ “); }

let employeeName = buildName(“Joseph”, “Samuel”, “Lucas”, “MacKinzie”); ```