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发生合并时,和它合并的namesapce不能访问它的未导出的成员:
namespace Animal {
const haveMuscles = true;
export function animalsHaveMuscles() {
return haveMuscles;
namespace Animal {
export function doAnimalsHaveMuscles() {
return haveMuscles; // Error, because haveMuscles is not accessible here
可以看到无法访问haveMuscles,同时运行也会报错,可以结合编译后的例子看:
namespace和class、enum、function合并
和合并namespace一样,class可以访问namespace中导出的类型和值:
class Album {
label: Album.AlbumLabel;
namespace Album {
export class AlbumLabel {}
// observable.ts
export class Observable<T> {
// ... implementation left as an exercise for the reader ...
// map.ts
import { Observable } from "./observable";
Observable.prototype.map = function (f) {
// ... another exercise for the reader
但是这样编译器并不能提供良好的提示,所以需要扩展module的声明:
// observable.ts
export class Observable<T> {
// ... implementation left as an exercise for the reader ...
// map.ts
import { Observable } from "./observable";
declare module "./observable" {
interface Observable<T> {
map<U>(f: (x: T) => U): Observable<U>;
// 扩展声明
Observable.prototype.map = function (f) {
// ... another exercise for the reader
// consumer.ts
import { Observable } from "./observable";
import "./map";
let o: Observable<number>;
o.map((x) => x.toFixed());
如果在模块中,也可以在全局声明中来扩展:
// observable.ts
export class Observable<T> {
// ... still no implementation ...
// 在这里扩展
declare global {
interface Array<T> {
toObservable(): Observable<T>;
Array.prototype.toObservable = function () {
// ...