只要不产生冲突就是合法的。 一个普通的规则是值总是会和同名的其它值产生冲突除非它们在不同命名空间里, 类型冲突则发生在使用类型别名声明的情况下( type s = string
), 命名空间永远不会发生冲突。
让我们看看如何使用。
利用interface
添加
我们可以使用一个interface
往别一个interface
声明里添加额外成员:
interface Foo {
x: number;
}
// ... elsewhere ...
interface Foo {
y: number;
}
let a: Foo = ...;
console.log(a.x + a.y); // OK
这同样作用于类:
class Foo {
x: number;
}
// ... elsewhere ...
interface Foo {
y: number;
}
let a: Foo = ...;
console.log(a.x + a.y); // OK
注意我们不能使用接口往类型别名里添加成员(type s = string;
)
使用namespace
添加
namespace
声明可以用来添加新类型,值和命名空间,只要不出现冲突。
比如,我们可能添加静态成员到一个类:
class C {
}
// ... elsewhere ...
namespace C {
export let x: number;
}
let y = C.x; // OK
注意在这个例子里,我们添加一个值到C
的静态部分(它的构造函数)。 这里因为我们添加了一个 值,且其它值的容器是另一个值 (类型包含于命名空间,命名空间包含于另外的命名空间)。
我们还可以给类添加一个命名空间类型:
class C {
}
// ... elsewhere ...
namespace C {
export interface D { }
}
let y: C.D; // OK
在这个例子里,直到我们写了namespace
声明才有了命名空间C
。 做为命名空间的 C
不会与类创建的值C
或类型C
相互冲突。
最后,我们可以进行不同的合并通过namespace
声明。 Finally, we could perform many different merges usingnamespace
declarations. This isn't a particularly realistic example, but shows all sorts of interesting behavior:
namespace X {
export interface Y { }
export class Z { }
}
// ... elsewhere ...
namespace X {
export var Y: number;
export namespace Z {
export class C { }
}
}
type X = string;
在这个例子里,第一个代码块创建了以下名字与含义:
- 一个值
X
(因为namespace
声明包含一个值,Z
) - 一个命名空间
X
(因为namespace
声明包含一个值,Z
) - 在命名空间
X
里的类型Y
- 在命名空间
X
里的类型Z
(类的实例结构) - 值
X
的一个属性值Z
(类的构造函数)
第二个代码块创建了以下名字与含义:
- 值
Y
(number
类型),它是值X
的一个属性 - 一个命名空间
Z
- 值
Z
,它是值X
的一个属性 - 在
X.Z
命名空间下的类型C
- 值
X.Z
的一个属性值C
- 类型
X
使用export =
或import
一个重要的原则是export
和import
声明会导出或导入目标的所有含义。
标签:TypeScript
相关阅读 >>
angular cli如果搭建angular+typescript+material项目?
更多相关阅读请进入《typescript》频道 >>

Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者