typescript基础篇(4):函数

时间:2022-07-23
本文章向大家介绍typescript基础篇(4):函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

4. 函数

函数在前面的章节已经多次使用,本节将梳理ts函数的知识。

回顾ts,定义一个函数有四种写法:

// 1.直接定义
let add1 = (x: number, y: number) => x + y

/*** 以下只是定义函数类型 */

// 2.类型注解
let add2: (x: number, y: number) => number

// 3.类型别名
type add3 = (x: number, y: number) => number

// 4.接口定义
interface add4 {
  (x: number, y: number): number
}

4.1 不定参数

我们在调用函数时,入参多一个不行,少一个也不行。

add1(1) // 报错,参数少了
add1(1,2,3) // 报错,参数多了

有时候我们需要传入不定个数的参数,此时可用?调用可选参数

// 注意可选参数必须在必选参数之后
const add5 = (x: number, y?: number) => (y ? x + y : x)
// 参数默认值
const add6 = (x: number, y = 0, z: number, q = 1) => x + y + z + q
// 剩余参数不用也可以
console.log(add6(1, undefined, 3)) // 4

实现叠加器:

const add7 = (x: number, ...rest: number[]) =>
  x + rest.reduce((pre, cur) => pre + cur)
add7(1,2,3,4) //10

4.2 函数重载

两个同名函数,参数不同(个数,类型)就实现了一个函数重载。重载的好处是,不需要给两个函数功能相似的方法,写两套函数。接下来看ts的例子。

Ts实现一个add函数,如果参数全是数字,则返回相加之和,如果参数全是字符串,则返回对应拼接。

// 声明
function add8(...rest: number[]): number
function add8(...rest: string[]): string
// 具体实现
function add8(...rest: any[]): any {
  let first = rest[0]
  if (typeof first == "string") {
    return rest.join("")
  }
  if (typeof first == "number") {
    return rest.reduce((pre, cur) => pre + cur)
  }
}

console.log(add8(1,2,3)) //6
console.log(add8('a','b','c')) //abc