将多个相同的声明合并为一个
接口 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 () {
// ...
};