跳到主要内容

命名空间

随着更多验证器的加入,我们需要一种手段来组织代码,以便于在记录它们类型的同时还不用担心与其它对象产生命名冲突。 因此,我们把验证器包裹到一个命名空间内,而不是把它们放在全局命名空间下。通过namespace 来声明命名空间,通过export来导出验证器以供外部访问,没有通过export导出的验证器外部是不可以访问的。

单文件命名空间


index.ts
namespace Home {
export type ListType = {
label: string;
}
}

namespace Me {
export type ListType = {
name: string;
}
}

const list1: Home.ListType = {
label: '哈哈'
}
const list2: Me.ListType = {
name: '嘻嘻'
}

多文件命名空间


因为不同文件之间存在依赖关系,所以我们加入了引用标签///<reference path="./home.ts" />来告诉编译器文件之间的关联

home.ts
namespace Home {
export type ListType = {
label: string;
}
}
me.ts
namespace Me {
export type ListType = {
name: string;
}
}
index.ts
///<reference path="./home.ts" />
///<reference path="./me.ts" />

const list1: Home.ListType = {
label: '哈哈'
}
const list2: Me.ListType = {
name: '嘻嘻'
}

console.log(list1);
console.log(list2);
修改 typescript.json 配置,将多个输入文件编译为一个输出文件,确保所有编译后的代码都被加载了
{
"compilerOptions": {
"target": "es2016",
"module": "amd",
"outFile": "./build/index.js",
"outDir": "./build",
"rootDir": "./src",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}