CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
TypeScript 进阶/课时/命名空间
RawBlame
课时目录12 节

TypeScript 进阶

  1. 01TS 进阶地图
  2. 02原始类型深入
  3. 03集合类型
  4. 04断言与收窄
  5. 05内置工具类型
  6. 06高级类型
  7. 07类与 OOP
  8. 08函数类型进阶
  9. 09装饰器
  10. 10命名空间
  11. 11工具链
  12. 12综合练习

命名空间

namespaces、augmentation、global augmentation。

25 分钟

命名空间

在 ES Module 成为主流之前,TypeScript namespace 用于组织代码与避免全局污染。现代项目优先 import/export,但读懂遗留库、做 模块增强(module augmentation) 与 全局类型扩展 仍需 namespace 知识。本课补充 typescript-essentials 模块课未覆盖的内容,并说明与 nestjs-essentials、nextjs-essentials 第三方类型声明的关系。

学习目标

  • 理解 namespace vs ES Module 的取舍
  • 使用 declare module 增强第三方库类型
  • 编写 global augmentation 扩展全局类型

基本 namespace

namespace Validation {
  export interface StringValidator {
    isValid(s: string): boolean;
  }

  export class EmailValidator implements StringValidator {
    isValid(s: string): boolean {
      return s.includes("@");
    }
  }
}

const validator = new Validation.EmailValidator();

嵌套与合并

namespace App {
  export namespace Models {
    export interface User {
      id: number;
      name: string;
    }
  }
}

// namespace 可声明合并
namespace App.Models {
  export interface User {
    email?: string;
  }
}

const user: App.Models.User = { id: 1, name: "Lee" };

模块增强 Module Augmentation

// types/express.d.ts
import "express";

declare module "express-serve-static-core" {
  interface Request {
    userId?: number;
  }
}

// 之后在 middleware 中
// req.userId 有类型提示

全局增强 Global Augmentation

// types/global.d.ts
export {};

declare global {
  interface Window {
    __APP_CONFIG__?: {
      apiBase: string;
    };
  }

  namespace NodeJS {
    interface ProcessEnv {
      DATABASE_URL: string;
      NODE_ENV: "development" | "production" | "test";
    }
  }
}

namespace 与模块互操作

// 不推荐新代码使用,但阅读 .d.ts 时会遇到
export namespace Utils {
  export function formatDate(d: Date): string {
    return d.toISOString();
  }
}

// 现代写法
export function formatDate(d: Date): string {
  return d.toISOString();
}

练习

  • 为 Express Request 增加 字段的类型增强
tenantId
  • 在 global.d.ts 扩展 ProcessEnv 添加项目环境变量
  • 找出一个 @types/* 包中使用 namespace 的声明文件并解读
  • 小结

    新代码用 ES Module;namespace 主要用于 .d.ts 增强与阅读遗留类型声明。 下一课工具链。

    加载本节练习…
    ← 上一课装饰器下一课 →工具链