namespace vs module
在 TypeScript 1.5 版本之前, TS 中存在 内部模块
和 外部模块
的概念。但是从 1.5 开始,为了兼容 ES6 中的模块语法,将 内部模块
改为了 命名空间
。而 外部模块 则称为 模块
,此时的 模块(module)
概念与 ES6 中的 模块 保持一致。
namespace 介绍
namespace
的概念与module
非常相似,主要都用于组织代码。在实际的开发中推荐尽量使用 module
来满足需求。
namespace 引用方式
需要注意的是,namespace
之间引用的时候, 采用 /// <reference path="namespaceName.ts" />
的语法来互相引用,而不遵循 module
中 import
规范。
namespace 主要场景
namespace
可以用于组织代码,聚合多个类等场景,但是此种场景推荐使用 ES6 module
。不过当我们需要在类型声明文件(*.d.ts)中描述一个带有多个函数和属性的第三方库的时候,会使用到 namespace
。例如下方例子:
/*~ If your library has properties exposed on a global variable,
*~ place them here.
*~ You should also place types (interfaces and type alias) here.
*/
declare namespace myLib {
//~ We can write 'myLib.timeout = 50;'
let timeout: number;
//~ We can access 'myLib.version', but not change it
const version: string;
//~ There's some class we can create via 'let c = new myLib.Cat(42)'
//~ Or reference e.g. 'function f(c: myLib.Cat) { ... }
class Cat {
Ï;
constructor(n: number);
//~ We can read 'c.age' from a 'Cat' instance
readonly age: number;
//~ We can invoke 'c.purr()' from a 'Cat' instance
purr(): void;
}
//~ We can declare a variable as
//~ 'var s: myLib.CatSettings = { weight: 5, name: "Maru" };'
interface CatSettings {
weight: number;
name: string;
tailLength?: number;
}
//~ We can write 'const v: myLib.VetID = 42;'
//~ or 'const v: myLib.VetID = "bob";'
type VetID = string | number;
//~ We can invoke 'myLib.checkCat(c)' or 'myLib.checkCat(c, v);'
function checkCat(c: Cat, s?: VetID);
}