typescript 文档阅读笔记-Declaration Merging

将多个相同的声明合并为一个

接口 interface 合并

  • 如果被合并的接口有相同的 key(key 为非函数成员),但是他们的 key 的值对应类型不一致,那么会报错。
  • 对于函数成员,如果他们的 key 相同,但是函数类型不一致,那么会被当做函数重载

namespaces 合并

  • 对于使用 export 导出的成员,会被合并
namespace Animals {
  export class Zebra {}
}
namespace Animals {
  export interface Legged {
    numberOfLegs: number;
  }
  export class Dog {}
}
// is equivalent to:

namespace Animals {
  export interface Legged {
    numberOfLegs: number;
  }
  export class Zebra {}
  export class Dog {}
}
  • 对于未使用 export 导出的成员,各命名空间之间互相不可见
namespace Animal {
  let haveMuscles = true;
  export function animalsHaveMuscles() {
    return haveMuscles;
  }
}
namespace Animal {
  export function doAnimalsHaveMuscles() {
    return haveMuscles; // Error, because haveMuscles is not accessible here
  }
}

namespace 与 classes、function、enums合并

在声明了 class、function、enums 之后,可以未其声明 namespace,namespace 会自动与其进行合并。例如:

我们可以使用 namespace 对 class、function、enums 内部添加类型声明或者变量等。但是记得使用 export 将成员导出,否则不会对外可见

class Album {
  label: Album.AlbumLabel;
}
namespace Album {
  export class AlbumLabel {}
}
--------------
function buildLabel(name: string): string {
  return buildLabel.prefix + name + buildLabel.suffix;
}
namespace buildLabel {
  export let suffix = "";
  export let prefix = "Hello, ";
}
--------------
enum Color {
  red = 1,
  green = 2,
  blue = 4,
}
namespace Color {
  export function mixColor(colorName: string) {
    if (colorName == "yellow") {
      return Color.red + Color.green;
    } else if (colorName == "white") {
      return Color.red + Color.green + Color.blue;
    } else if (colorName == "magenta") {
      return Color.red + Color.blue;
    } else if (colorName == "cyan") {
      return Color.green + Color.blue;
    }
  }
}
Color.mixColor('yellow')

全局声明 global

You can also add declarations to the global scope from inside a module

// observable.ts
export class Observable<T> {
  // ... still no implementation ...
}
declare global {
  interface Array<T> {
    toObservable(): Observable<T>;
  }
}
Array.prototype.toObservable = function () {
  // ...
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值