TypeScript学习笔记-声明合并

类不能和其他的类或者变量合并

/**
 * 声明合并
 * 若两个接口中存在相同的参数,那么这些相同的参数必须有相同的类型
 * 若两个接口中存在相同的函数,那么同名的函数声明都会被当成这个函数的重载,且后面的接口有更高的优先级
 */
interface Box {
  height: number;
  width: number;
  clone(animal: Sheep): Sheep;
}

interface Box {
  scale: number;
  clone(animal: Dog): Dog;
}

let animal: Sheep;
let box: Box = { width: 20, height: 20, scale: 30, clone(animal) {} };
/**
 * 命名空间和类的合并
 * **********
 * 这让我们可以表示内部类
 * **********
 * 合并后的命名空间只能互相访问已经导出的成员
 */

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 prefix = "Hello";
  export let suffix = "";
}

buildLabel("zhangsan");

//枚举和命名空间的合并
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;
    }
  }
}

 

posted @ 2018-10-11 16:22  CodingSherlock  阅读(529)  评论(0编辑  收藏  举报