# 函数

# 函数声明与函数表达式











 



// function declaration

function sum(x: number, y: number): number {
  return x + y;
}

console.log(sum(1, 23));

// function expression

const mySum: (x: number, y: number) => number = (a, b) => a + b; // 注意区分两个=>, 它们不一样

console.log(mySum(2, 2));
1
2
3
4
5
6
7
8
9
10
11
12
13

# 使用接口定义函数

interface ISum {
  (x: number, y: number): number;
}

const iSum: ISum = (m, n) => m + n;

console.log(iSum(3, 4));
1
2
3
4
5
6
7

# 可选参数

interface IOptionalSum {
  (x: number, y: number, z?: number): number;
}

const iOptionalSum: IOptionalSum = (a, b, c) => {
  if (c) {
    return a + b + c;
  } else {
    return a + b;
  }
};
1
2
3
4
5
6
7
8
9
10
11

WARNING

可选参数必须接在必需参数后面. 换句话说, 可选参数后面不允许再出现必需参数了.

# 默认参数

TypeScript 会将添加了默认值的参数识别为可选参数:

function add(m: number, b: number = 999): number {
  return m + b;
}

console.log(add(1)); //1000
console.log(add(1, 1)); // 2
1
2
3
4
5
6

# 剩余参数

function push(array: number[], ...items: number[]) {
  items.forEach(function(item) {
    array.push(item);
  });
}

let a = [];
push(a, 1, 2, 3);
console.log(a); // [1,2,3]
1
2
3
4
5
6
7
8
9