typescript - 为什么 ES2015 模块语法优于自定义 TypeScript 命名空间?

标签 typescript module namespaces typescript-typings .d.ts

来自 typescript-eslint docs :

Custom TypeScript modules (module foo {}) and namespaces (namespace foo {}) are considered outdated ways to organize TypeScript code. ES2015 module syntax is now preferred (import/export).


来自 typescript docs

Modules can contain both code and declarations.

Modules also have a dependency on a module loader (such as CommonJs/Require.js) or a runtime which supports ES Modules. Modules provide for better code reuse, stronger isolation and better tooling support for bundling.

It is also worth noting that, for Node.js applications, modules are the default and we recommended modules over namespaces in modern code.


我对这个问题的目标是找出为什么模块语法比命名空间更受欢迎。
到目前为止,这是我一直在做的事情:
PROJECT_TYPES.d.ts
我有多个 d.ts我在其中声明包含我在项目源文件中使用的类型的命名空间的文件。
declare namespace MY_NAMESPACE {
  type FOO = "FOO"
}
这样做,我可以在我的项目的任何源文件中执行以下操作:
someFile.ts
const foo: MY_NAMESPACE.FOO =  "FOO";
它无需任何 import 即可工作/export .
备注:
  • 我正在使用 d.ts文件,因为这些文件不包含任何 import/export代码。
  • 我正在使用 declare namespace而不仅仅是 namespace因为没有 declare关键字我得到一个 @typescript-eslint/no-unused-vars警告。

  • 考虑到 MY_NAMESPACE是一个独特的名字,这应该被认为是一种不好的做法吗?在这种情况下,我是否有理由使用 modulesnamespaces ?我应该不使用 d.ts文件?
    我的意思是,Typescript 文档提到:

    Modules provide for better code reuse, stronger isolation and better tooling support for bundling.


    但是我不认为遵循我上面描述的模式会失去任何这些好处,因为我所有的“真实”实际编译结果代码都在模块中分开。但是为什么我的类型应该只在模块中?

    最佳答案

    TLDRnamespace的目的是提供构造的逻辑分组,但是 ES2015 模块的引入允许我们使用文件系统来实现这一点,而不会污染全局范围。它还为我们在使用类型时提供了更大的灵活性。
    例子
    ES2015 前

    // src/geometry/types.d.ts
    declare namespace Geometry{
        export type Shape = 'circle' | 'square'
    }
    
    // src/geometry/main.ts
    let myShape: Geometry.Shape = 'square'
    
    ES2015 后
    // src/geometry/types.ts
    export type Shape = 'circle' | 'square'
    
    // src/geometry/main.ts
    import { Shape } from './types'
    let myShape: Shape = 'square'
    
    //src/geometry/index.ts
    export * as Geometry from './types'
    
    引用
  • Typescript Docs - tradeoffs and pitfalls
  • SO Answer - when to use namespaces
  • 关于typescript - 为什么 ES2015 模块语法优于自定义 TypeScript 命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64043495/

    相关文章:

    需要 XML 命名空间吗?

    c# - 以编程方式检查 Http 命名空间保留

    java - 为什么我的 xpath 不起作用?

    typescript - PowerBi-Javascript报告embedding cluster details 403错误

    javascript - JS 主应用程序使用路由来显示对话框等?

    java - 寻找 EJB3 的简化概述

    postgresql - 如何为通过 Homebrew 软件安装的 Postgresql 安装 Trigram 模块?

    javascript - ko 未定义错误 durandal

    angular - 自定义错误处理程序抛出错误 : Cannot read property 'get' of undefined ( Injector )

    css - ngStyle 内的插值