Skip to content

函数

函数定义

函数声明

ts
function sum(x: number, y: number): number {}

函数表达式

ts
let mySum: (x: number, y: number) => number = function (x: number, y: number): number {
  return x + y
}

接口定义函数类型

ts
interface SearchFunc {
  (source: string, subString: string): boolean
}

参数

可选参数

ts
// ?: type
function buildName(firstName: string, lastName?: string) {}

参数默认值

ts
// type = 'default'
function buildName(firstName: string, lastName: string = 'Cat') {}

剩余参数

ts
// ...variables = type[]
function push(array: any[], ...items: any[]) {}

函数重载

场景:不同类型的参数来调用同一个函数,返回不同的类型的结果

ts
function add(x, y) {
  return x + y
}
add(1, 2) // 3
add('1', '2') //"12"

开启 noImplicitAny 的配置项时,会报错,x,y 会隐式推断为 any

解决方案:定义联合类型

ts
type Combinable = string | number
function add(a: Combinable, b: Combinable) {
  if (typeof a === 'string' || typeof b === 'string') {
    return a.toString() + b.toString()
  }
  return a + b
}
js
const result = add('Semlinker', ' Kakuqo') // ok
result.split(' ') // Property 'split' does not exist on type 'number'

新问题:返回值类型可能为 number,不能直接调用 split

解决方案:为同一个函数提供多个函数类型定义来进行函数重载,编译器会根据这个列表去处理函数的调用。

ts
type Types = number | string
// 多个函数声明
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: string, b: number): string;
function add(a: number, b: string): string;
// 函数实现
function add(a: Types,  b: Types):  {
  if (typeof a === 'string' || typeof b === 'string') {
    return a.toString() + b.toString();
  }
  return a + b;
}