1. 程式人生 > 實用技巧 >9、TypeScript中的名稱空間

9、TypeScript中的名稱空間

名稱空間:

  在程式碼量較大的情況下,為了避免各種變數名相沖突,可以將相識的功能的函式、類、介面等放置在名稱空間中。

  同java的包、.net的名稱空間一樣,Typescript的名稱空間可以將程式碼包裹起來,只對外暴露需要訪問的物件,名稱空間內的物件通過export暴露。

名稱空間和模組的區別:

  名稱空間:內部模組,主要用於組織程式碼,避免命名衝突。

  模組:ts的外部模組的簡稱,側重程式碼的複用,一個模組裡可能會有多個名稱空間。

在modules中定義一個檔案name.ts

export namespace A{
  interface Animal{
    name:string;
    eat():
void; } export class Dog implements Animal{ name:string; constructor(theName:string){ this.name = theName } eat(){ console.log(`${this.name}在吃狗糧`); } } export class Cat implements Animal{ name:string; constructor(theName:string){ this.name = theName } eat(){ console.log(`${
this.name}在吃貓糧`); } } } export namespace B{ interface Animal{ name:string; eat():void; } export class Dog implements Animal{ name:string; constructor(theName:string){ this.name = theName } eat(){ console.log(`${this.name}在吃狗糧`); } } export class Cat implements Animal{ name:string; constructor(theName:string){
this.name = theName } eat(){ console.log(`${this.name}在吃貓糧`); } } }

namespace.js中引入並使用

import {A,B} from './modules/name'

var d = new A.Dog('哈士奇小黑');
d.eat()

var c = new B.Cat('小花');
c.eat()
exportnamespaceA{ interfaceAnimal{ name:string; eat():void; } exportclassDogimplementsAnimal{ name:string; constructor(theName:string){ this.name=theName } eat(){ console.log(`${this.name}在吃狗糧`); } }
exportclassCatimplementsAnimal{ name:string; constructor(theName:string){ this.name=theName } eat(){ console.log(`${this.name}在吃貓糧`); } } }

exportnamespaceB{ interfaceAnimal{ name:string; eat():void; } exportclassDogimplementsAnimal{ name:string; constructor(theName:string){ this.name=theName } eat(){ console.log(`${this.name}在吃狗糧`); } }
exportclassCatimplementsAnimal{ name:string; constructor(theName:string){ this.name=theName } eat(){ console.log(`${this.name}在吃貓糧`); } } }