# 十七.模块和命名空间

前言

  • 命名空间(Namespace)用于组织和封装相关的代码,以避免全局命名冲突,并提供更好的代码结构和模块化。
  • 模块可以将相关的功能分组到独立的单元中,具有更好的可维护性、可复用性和可测试性。

# 1.模块

文件模块:如果在你的 TypeScript 文件的根级位置含有import或者export,那么它会在这个文件中创建一个本地的作用域

// a.ts 导出
exprot default 'aaa'

//index.ts 导入
import name from './a'
1
2
3
4
5

# 2.命名空间

命名空间可以用于组织代码,避免文件内命名冲突

# 2.1 使用

  • 在需要使用得地方放入
// type.d.ts
export namespace zoo {
  export class Dog {
    eat() {
      console.log("zoo dog")
    }
  }
}
export namespace home {
  export class Dog {
    eat() {
      console.log("home dog")
    }
  }
}

let dog_of_zoo = new zoo.Dog()
dog_of_zoo.eat()
let dog_of_home = new home.Dog()
dog_of_home.eat()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 2.2 间嵌套使用

export namespace zoo {
  export class Dog { eat () {
    console.log('zoo dog')
  }}
  export namesapce bear{
    export const name ='xxxx'
  }
}
console.log(zoo.bear.name)
1
2
3
4
5
6
7
8
9

命名空间中导出的变量可以通过命名空间使用

# 3.案例

# 3.1 接口

interface IPageData<T = any> {
  data: T[]
}

interface IResponseData<T = any> {
  msg: string
  result: T
}
// 搜索
export declare namespace TextSearchType {
  interface RequestParams {
    pageSize: string
    currentPage: string
    id: string
    name?: string
    description?: string
  }
  interface ResponseData extends IResponseData<IPageData<T>> {
    msg?: string
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 3.2 类型

// 编辑
export declare namespace NftEditType {
  type Params1 = {
    id: string
    name: string
  }
  type Params2 = {
    id: string
    code?: string
  }
  type RequestParams = Params1 & Params2
}
1
2
3
4
5
6
7
8
9
10
11
12