Skip to content

命名空间 in TypeScript

组织 code 使用命名空间 (内部模块) and 理解当 到 prefer ES 模块.

你将学到

  • 如何 定义 and use 命名空间使用命名空间 keyword
  • Nested 命名空间 and 点语法
  • 命名空间合并跨越 files
  • 为什么 ES 模块是 preferred over 命名空间 in modern code

概念讲解

The Namespace Keyword

A namespace is a named container for related declarations, defined with the 命名空间 keyword: 命名空间 Geometry { 导出 函数 区域() {} }. You access members with dot syntax: Geometry.区域(). Namespaces predate ES modules and were TypeScript's original way to avoid global scope pollution. They are still found in older codebases and in declaration files for global libraries.

Nested and Merged Namespaces

Namespaces can be nested: 命名空间 App.Utils { 导出 函数 格式() {} } accessed as App.Utils.格式(). Namespaces also merge — declaring the same namespace name in multiple files combines their members. This merging is useful for extending a namespace across files without imports, but it can also lead to confusion about where a member is defined.

Namespaces vs Modules

In modern TypeScript, ES modules are strongly preferred over namespaces. Modules have explicit dependencies (import/export), better tooling support (tree-shaking, code splitting), and are the JavaScript standard. Namespaces create implicit global containers that are harder to reason about. Use namespaces only when working with legacy code or when writing declaration files for global libraries that cannot use modules.

示例代码

              // Define a namespace to group related functions.
namespace Geometry {
  export const PI = 3.14159;

  export function circleArea(radius: number): number {
    return PI * radius * radius;
  }

  export function squareArea(side: number): number {
    return side * side;
  }
}

// Nested namespace.
namespace App {
  export namespace Utils {
    export function formatPrice(value: number): string {
      return "$" + value.toFixed(2);
    }
  }
}

// Namespace merging — same name in different files combines members.
namespace Geometry {
  export function triangleArea(base: number, height: number): number {
    return 0.5 * base * height;
  }
}

console.log(Geometry.circleArea(5));
console.log(Geometry.squareArea(4));
console.log(Geometry.triangleArea(6, 8));
console.log(App.Utils.formatPrice(19.999));
            

命名空间分组 related code 使用命名空间 keyword. 它们能 nest and 合并跨越 files. 然而, ES 模块是 preferred in modern code for explicit dependencies and better tooling.

动手试一试

  • Code Minifier

    See 如何命名空间编译到 JavaScript 对象对比模块模式.

  • Code Diff

    Compare 命名空间-based code 使用 equivalent ES 模块 version.

常见错误

错误写法

Using 命名空间 in 新项目相反的 ES 模块

正确做法

ES 模块是 modern 标准使用 better tooling, 树-shaking, and explicit dependencies. Use 命名空间仅 for legacy code or 全局库 declarations.

错误写法

Forgetting 到导出成员内部命名空间

正确做法

命名空间成员是 私有通过默认. Use 导出 keyword 内部命名空间到 制作它们 accessible 从之外, 只是如 模块导出.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误