typescript——函数的定义

函数声明法

function run (name: string, age: number): string {
  return `${name}---${age}`
}

run('bob', 14)

匿名函数法

let run = function (num: number): number {
  return num
}

run(18)

箭头函数法

let run = (name: string, age: number): string => {
  return `my name is ${name} , i am ${age}`
}

run('john', 30) // my name is john , i am 30

无返回值

let run = function (): void {
  console.log(123)
}

run()

可选参数

  • 参数 ?: 数据类型
  • 注意:可选参数必须配置到参数最后一项,否则警告
function run (name: string, age?: number): string {
  if (age) {
    return `${name}---${age}`
  } else {
    return `${name}---年龄保密`
  }
}

run('lucy')

默认可选参数

function run (name: string, age: number = 18): string {
  return `${name}---${age}`
}

run('tom')

解构参数

function run1 ([first, second]: [number, number]) {
    return first + second
}
function run2 ({first, second}: {first: number, second: number}) {
    return first + second
}
function run3 ({first, second}: any) {
    return first + second
}

剩余参数

function run (a: number, b: number, ...args: number[]): number {
  return a + b + args.reduce((v1, v2) => {
    return v1 + v2
  })
}

run(1, 2, 3, 4, 5) // 第一二个数指向 a b ,剩余指向 args

函数重载 (es5 中没有重载概念,会后面的替换前面的)

重载指的是两个或两个以上的同名函数,但它们的参数不一样,这时会出现重载情况

function run1 (name: string): string;
function run1 (age: number): number;
function run1 (str: any): any {
  if (typeof str === 'string') {
    return `my name ${str}`
  } else {
    return `i am ${str}`
  }
}

run1('bob') // my name bob
run1(18) // i am 18

function run2 (name: string): string;
function run2 (name: string, age: number): number;
function run2 (name: any, age?: any): any {
  if (age) {
    return `my name ${name} , i am ${age}`
  } else {
    return `my name ${name}`
  }
}

run2('lucy') // my name lucy
run2('lucy', 18) // my name lucy , i am 18

你可能感兴趣的:(typescript)