# 函数的类型

# 函数声明

function sum(x, y) {
  return x + y
}

function sum(x: number, y: number): number {
  return x + y
}
1
2
3
4
5
6
7

# 函数表达式

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

const sum: (x: number, y: number) => number = function(x: number, y: number): number {
  return x + y
}
1
2
3
4
5
6
7

#接口 定义函数的形状

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

const sum: ISumFn = function(x: number, y: number): number {
  return x + y
}
1
2
3
4
5
6
7

# 可选参数

  • 可选参数后面不允许再出现必需参数了
// 可选参数
const getFullName = function(fName: string, lName?: string): string {
  return fName + lName;
}

getFullName('Ben', 'Lee');
getFullName('Ben');
1
2
3
4
5
6
7

# 默认参数值

const getFullName2 = function(fName: string, lName: string = 'lee'): string {
  return fName + lName;
}

const getFullName2 = function(fName: string = 'hello', lName: string): string {
  return fName + lName;
}
1
2
3
4
5
6
7

# 剩余参数

  • ...rest
function Push(array: any[], ...items: any[]) {
  items.forEach(i => {
    array.push(i)
  })
}

const a1: any[] = []
Push(a1, 1,2,3)
1
2
3
4
5
6
7
8