TypeSript9 命名空间namesapce

我们在工作中无法避免全局变量造成的污染,TypeScript提供了namespace 避免这个问题出现

  • 内部模块,主要用于组织代码,避免命名冲突。
  • 命名空间内的类默认私有
  • 通过 export 暴露
  • 通过 namespace 关键字定义

TypeScript与ECMAScript 2015一样,任何包含顶级import或者export的文件都被当成一个模块。相反地,如果一个文件不带有顶级的import或者export声明,那么它的内容被视为全局可见的(因此对模块也是可见的)

ok,让我们看一个小例子

命名空间中通过export将想要暴露的部分导出

如果不用export 导出是无法读取其值的

namespace a {

export const Time: number = 1000

export const fn = <T>(arg: T): T => {

return arg

}

fn(Time)

}

namespace b {

export const Time: number = 1000

export const fn = <T>(arg: T): T => {

return arg

}

fn(Time)

}

a.Time

b.Time

嵌套命名空间

namespace a {

export namespace b {

export class Vue {

parameters: string

constructor(parameters: string) {

this.parameters = parameters

}

}

}

}

let v = a.b.Vue

new v('1')

抽离命名空间

a.ts

export namespace V {

export const a = 1

}

b.ts

import {V} from '../observer/index'

console.log(V);

//{a:1}

简化命名空间

namespace A {

export namespace B {

export const C = 1

}

}

import X = A.B.C

console.log(X);

合并命名空间

TypeSript10 模块学习-CSDN博客

相关推荐
用户0566949483121 小时前
🔥 我把 axios 接口封装,玩出了 NestJS 的感觉
typescript
索西引擎1 天前
【理论】TypeScript 函数重载:从 Vue 3 defineEmits 说起的类型安全实践
前端·typescript
漫游的渔夫1 天前
从 if-else 乱麻到状态机:前端开发者该怎么理解多 Agent 协作?
前端·人工智能·typescript
matrixmind81 天前
sindresorhustype-fest:TypeScript 工具类型集合
前端·javascript·其他·typescript
guangzan2 天前
DeepSeek-Lane:在 Cursor 内使用 DeepSeek V4 模型
typescript
晓杰'2 天前
从0到1实现 Balatro 游戏后端(1):项目规划与牌型判断实现
后端·websocket·typescript·node.js·游戏开发·项目实战·nestjs
Forget the Dream2 天前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式
烛衔溟3 天前
TypeScript 接口继承与混合类型
linux·ubuntu·typescript
送鱼的老默3 天前
学习笔记--入门typescript直接案例开搞
前端·typescript
spmcor3 天前
TypeScript 中 null 与 undefined 的区别 —— 一篇彻底搞懂的指南
typescript