这在 Typescript 中是一个不好的做法吗?我有什么选择?

发布于 2025-01-16 04:35:58 字数 515 浏览 3 评论 0原文

我希望有一个一致的类实例(本例中的集合)可以在整个项目中使用。 我正在使用 Typescript,所以我想解决在没有任何类型安全的情况下以 JavaScript 风格创建一些奇怪对象的概念。

由于我不需要在任何地方传递此类的真实对象,因此我完全同意拥有一个仅包含静态成员的类的想法,我可以通过调用类名在项目中访问该类。 这个概念有什么问题吗? 我应该使用单例模式,然后在文件末尾执行 export Collection.getInstance() 吗?

export class CollectionInstance{
  static readonly exampleCollection = new ExampleCollection();

  //noinspection JSUnusedLocalSymbols
  private constructor() {
  }

  public static load(){

  }

  public static get(key: string){

  }
}

I want to have a consistent instance of a class (a collection in this example) to work in the whole project with.
I am using Typescript so I want to work around the concept of creating some wonky object in the JavaScript-style without any type safety.

As I don't need to pass a real object of this class anywhere, I am completely fine with the idea of having a class with only static members, which I can access in the project by calling the class name.
Is there anything wrong with this concept?
Should I use a singleton pattern and then just do export Collection.getInstance() at the end of the file?

export class CollectionInstance{
  static readonly exampleCollection = new ExampleCollection();

  //noinspection JSUnusedLocalSymbols
  private constructor() {
  }

  public static load(){

  }

  public static get(key: string){

  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文