TS学习笔记(十):命名空间

在确保咱们建立的变量不会泄露至全局变量中,咱们之前曾采用过这种代码组织形式:typescript

(function(someObj){
    someObj.age = 18;
})(someObj || someObj = {});

复制代码

但在基于文件模块的项目中,咱们无须担忧这一点,此种方式,适合用于合理的函数逻辑分组中,在 TypeScript 中,提供了 namespace 关键字来描述这种分组,在 typescript 编译器进行编译事后,命名空间也就被编译成了上述示例那样的代码。函数

命名空间的声明

TypeScript 的命名空间只对外暴露须要在外部访问的对象,命名空间内的对象经过 export 关键字对外暴露,好比咱们在一个名叫 utils.ts 的文件里声明一个命名空间:ui

// utils.ts
namespace Utils {
    export interface IPerson {
        name: string;
        age: number;
    }
}
复制代码

命名空间的使用

经过 namespace 关键字声明命名空间,在命名空间外部须要经过彻底限定名访问这些对象,一般状况下,声明的命名空间代码和调用的代码不在同一个文件里,所以在其余文件中使用,注意引入的路径要写正确,此处咱们在同级目录中任意一个 ts 文件中使用咱们刚定义的命名空间:this

/// <reference path="utils.ts" />
const me: Utils.IPerson = {
    name: 'funlee',
    age: 18
}
console.log(me); // {name: 'funlee', age: 18}

复制代码

如上述代码所示,经过 reference 注释引用命名空间,便可经过彻底限定名进行访问,咱们也能够经过 import 导入模块的形式,引入命名空间:spa

import './utils'

const me: Utils.IPerson = {
    name: 'funlee',
    age: 18
}
console.log(me); // {name: 'funlee', age: 18}

复制代码

多文件的命名空间

就像普通的 JS 模块文件能够相互引用同样,包含 namespace 的命名空间文件也能够相互引入,还能够组合成一个更大的命名空间,下面是一个简单的示例,全部文件都在同一目录下,你也可参考官方示例:code

utils.ts对象

namespace Utils {
    export interface IAnimal {
        name: string;
        say(): void;
    }
}
复制代码

animal.tsip

/// <reference path="utils.ts" />

export namespace Animal {
    export class Dog implements Utils.IAnimal{
        name: string;
        constructor(theName: string) {
            this.name = theName;
        }
        say() {
            console.log(`${this.name}: 汪汪汪`)
        }
    }
}
复制代码

index.ts编译器

import {Animal} from './animal';

const he = new Animal.Dog('Jack');
he.say(); // Jack: 汪汪汪

复制代码
相关文章
相关标签/搜索