如何在不导入的情况下在打字稿中的多个文件中使用相同的枚举

发布于 2025-01-28 22:17:59 字数 1343 浏览 2 评论 0原文

现在,我一直在为此苦苦挣扎,比我应该更长的时间,令人惊讶的是,现有问题(和很多问题)并没有真正帮助。

我的目标是在全局级别上声明并定义enum ,以便我可以在任何文件中使用所述enum,而无需导入它们。 现在,据我了解,您不能使用d.ts文件来完成此操作。我还看到了其他工作(例如,这是 https://githbithub.com/microsoft.com/microsoft/typescript/问题/14975 )似乎不是最好的实践,而是“修复”。或问题,这些问题尚未得到完全回答(例如 typescript d.ts d.ts d.ts文件中的枚举)

现在,显然要走的方法是创建common.ts并处理该文件中的任何enum。我必须如何进行才能实现这一目标:

某些global.ts file

 enum someEnum{
        first = 'someString',
        second = "someOtherString'
    }

a.ts file

//without any imports
const myFirstEnumValue = someEnum.first // resulting in "someString"

上下文

我正在编写一个React,Electron App,并且不想声明/定义我的枚举两次,在electron.ts中(有时称为main) React文件。这在typesinterfaces的情况下起作用。代码>在tsconfig.json中),但不是enums

I've been struggling with this now longer than I should and surprisingly, the existing questions (and there are many) don't really help further.

My goal is to declare and define enum on a global level, such that I can use that said enum in any file without having to import them.
Now, to my understand you can't do this with a d.ts file. I also saw other work arounds (e.g. this one https://github.com/Microsoft/TypeScript/issues/14975 ) that don't seem best-practice but rather a "fix". Or questions, that aren't fully answered (e.g. Enums in typescript d.ts file )

Now, apparently a way to go is to create a common.ts and handle any enum in that file. How exactly do I have to proceed in order to make this possible:

Some global.ts file

 enum someEnum{
        first = 'someString',
        second = "someOtherString'
    }

a.ts file

//without any imports
const myFirstEnumValue = someEnum.first // resulting in "someString"

Context

I'm writing a React, Electron App and don't want to declare/define my enums twice, in electron.ts (sometimes called main) and in any react file. This works without any issue with types and interfaces in a file called types.d.ts (filepath is added to typeRoots in tsconfig.json) but again, not with enums

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

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

发布评论

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