TypeScript 声明合并

207 阅读2分钟

合并接口

  • 接口的非函数的成员应该是唯一的。如果它们不是唯一的,那么它们必须是相同的类型。

  • 对于函数成员,每个同名函数声明都会被当成这个函数的一个重载。 同时需要注意,当接口 A与后来的接口 A合并时,后面的接口具有更高的优先级。

  • 如果签名里有一个参数的类型是 单一的字符串字面量(比如,不是字符串字面量的联合类型),那么它将会被提升到重载列表的最顶端。


  interface Shape {
    height: number,
    width: number,
    createShape(shape: 'square'): void,
  }
  interface Shape {
    height: number,
    width: number,
    createShape(shape: 'rect'): void,
    createShape(shape: string): void,
  }
  interface Shape {
    radius: number,
    createShape(shape: 'cirle'): void,
  }
   // 这三个接口合并成
   interface Shape {
      radius: number,
      height: number,
      width: number,
      createShape(shape: 'cirle'): void,
      createShape(shape: 'rect'): void,
      createShape(shape: 'square'): void,
      createShape(shape: string): void,   
  }

合并命名空间

  namespace Animals {
      export class Zebra { }
  }

  namespace Animals {
      export interface Legged { numberOfLegs: number; }
      export class Dog { }
  }
  
  // 等同于
  
  namespace Animals {
    export interface Legged { numberOfLegs: number; }

    export class Zebra { }
    export class Dog { }
  }

非导出成员仅在其原有的(合并前的)命名空间内可见。这就是说合并之后,从其它命名空间合并进来的成员无法访问非导出成员。

  namespace Animal {
   let haveMuscles = true;

   export function animalsHaveMuscles() {
       return haveMuscles;
   }
 }

 namespace Animal {
     export function doAnimalsHaveMuscles() {
         return haveMuscles;  // Error, because haveMuscles is not accessible here
     }
 }

命名空间与类和函数和枚举类型合并

命名空间可以与其它类型的声明进行合并。 只要命名空间的定义符合将要合并类型的定义。合并结果包含两者的声明类型。 TypeScript使用这个功能去实现一些JavaScript里的设计模式。

  // 命名空间来表示内部类
  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, ";
 }
 console.log(buildLabel("Sam Smith"));
 
 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;
     }
   }
 }