Allen Yu Allen Yu
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
  • 开始

  • 基础

  • 进阶

    • 类型别名
    • 字符串字面量类型
    • 元组
    • 枚举
    • 类
    • 类与接口
    • 泛型
    • 声明合并
      • 声明合并 (Declaration Merging)
      • 函数的合并
      • 接口的合并
      • 类的合并
      • 参考
    • 工具类型
    • 编译配置
  • 实战

  • TypeScript
  • 进阶
2020-10-31
目录

声明合并

# 声明合并 (Declaration Merging)

如果定义了两个相同名字的函数、接口或类,那么它们会合并成一个类型。

# 函数的合并

之前学习过,我们可以使用函数重载定义多个类型:

function reverse(x: number): number
function reverse(x: string): number
function reverse(x: number | string): number | string {
  if (typeof x === 'number') {
    return Number(x.toString().split('').reverse().join(''))
  } else if (typeof x === 'string') {
    return x.split('').reverse().join('')
  }
}

# 接口的合并

接口中的属性,在合并时会简单的合并到一个接口中:

interface Alarm {
  price: number
}
interface Alarm {
  weight: number
}

相当于

interface Alarm {
  price: number
  weight: number
}

注意,合并的属性的类型必须是唯一的:

interface Alarm {
  price: number
}
interface Alarm {
  price: number
  weight: number
}

上例中,虽然属性 price 属性重复了,但因为类型都是 number,所以不会报错。

interface Alarm {
  price: number
}
interface Alarm {
  price: string
  weight: number
}
// 后续属性声明必须属于同一类型。属性“price”的类型必须为“number”,但此处却为类型“string”。ts(2717)

上例中,属性 price 重复了,且两次类型不一致,导致报错了。

接口中方法的合并,与函数的合并一样。

interface Alarm {
  price: number
  alert(s: string): string
}
interface Alarm {
  price: number
  weight: number
  alert(s: string, n: number): string
}

上面的代码合并后,相当于:

interface Alarm {
  price: number
  weight: number
  alert(s: string): string
  alert(s: string, n: number): string
}

# 类的合并

类的合并,和接口合并的规则一致。

# 参考

  • TypeScript 入门教程 - 声明合并 (opens new window)
Last Updated: 3/30/2022, 1:20:25 AM
泛型
工具类型

← 泛型 工具类型→

最近更新
01
4 月第 2 周总结
04-17
02
工具类型
04-01
03
Google 搜索小技巧
03-28
更多文章>
Theme by Vdoing | Copyright © 2018-2022 Allen Yu
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式