typescript - 我应该更喜欢命名空间还是带有静态函数的类?

标签 typescript

在 TypeScript 中,有两种可能的方法来捆绑和公开一组函数。一种是导出一个只包含公共(public)静态函数的类。另一种是创建命名空间,然后从其中导出函数。据我所知,这会在 TypeScript 中产生相同的行为(尽管可能会产生不同的 JavaScript)。是否有一种方法是首选的,或者它是否完全取决于个人偏好。

namespace MyCollection {
    export function doSomething(macguffin: any) {
        //todo: implement doSomething
    }
}

export class MyCollection {
    public static doSomething(macguffin: any) {
        //todo: implement doSomething
    }
}

最佳答案

最好使用模块而不是 namespace 或静态类方法。来自 namespaces and modules 上的 TypeScript 官方文档页面:

Namespaces are simply named JavaScript objects in the global namespace. [...] Just like all global namespace pollution, it can be hard to identify component dependencies, especially in a large application.

[...]

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

[...]

Starting with ECMAScript 2015, modules are native part of the language, and should be supported by all compliant engine implementations. Thus, for new projects modules would be the recommended code organization mechanism.

关于typescript - 我应该更喜欢命名空间还是带有静态函数的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415859/

相关文章:

javascript - 返回 html 上的 Angular 2+ onmouseover 事件

javascript - Angular 5 - react 形式 - 有没有办法使用变量来修补值?

javascript - 序列化 : How to exclude Entity columns in json response but not internal queries in Nestjs

angular - 获取对当前事件的 HTMLElement 的引用

reactjs - TypeScript 和自定义 React Hook Api 服务

Typescript 通过 in 运算符进行类型保护

Angular2 - 在指令中更改 innerHTML 时动态创建 routerLink

typescript - Firebase错误: Firebase: Firebase App named '[DEFAULT]' already exists with different options or config (app/duplicate-app)

Typescript 声明文件 - "export declare"和 "export"之间的区别

javascript - 无法从 $resource 中提取数据(使用 REST Web 服务)