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: 汪汪汪

複製代碼
相關文章
相關標籤/搜索