具有数值的JavaScript嵌套枚举

发布于 2025-02-02 00:11:27 字数 370 浏览 2 评论 0原文

目前,枚举的形状正常:

export enum CountryIndex {
  JAPAN = 0,
  CHINA = 1,
  INDIA = 2 
}

我需要在其中添加一个类别,例如大陆,以便看起来像这样:

export enum CountryIndex {
  ASIA: { JAPAN = 0,
          CHINA = 1,
          INDIA = 2
        },
  EUROPE: { SPAIN = 0,
            ITALY = 1
          }
}

上面的类别是不正确的,是否有一种方法可以使具有数值值的嵌套枚举?

Currently the enum has this shape which works fine:

export enum CountryIndex {
  JAPAN = 0,
  CHINA = 1,
  INDIA = 2 
}

I need to add a category inside of it, for example continents, in order to look like this:

export enum CountryIndex {
  ASIA: { JAPAN = 0,
          CHINA = 1,
          INDIA = 2
        },
  EUROPE: { SPAIN = 0,
            ITALY = 1
          }
}

The above one is not correct, is there a way to make a nested enum with numerical values?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山田美奈子 2025-02-09 00:11:27

枚举值的基础类型必须是字符串或数字。

您最接近的是使用对象。类似的东西

export const CountryIndex = {
  ASIA: {
    JAPAN: 0,
    CHINA: 1,
    INDIA: 2,
  },
  EUROPE: {
    SPAIN: 0,
    ITALY: 1 
 }
} as const

The underlying types for an enum values need to be either strings or numbers.

Your closest thing would be to use objects. Something similar to this

export const CountryIndex = {
  ASIA: {
    JAPAN: 0,
    CHINA: 1,
    INDIA: 2,
  },
  EUROPE: {
    SPAIN: 0,
    ITALY: 1 
 }
} as const
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文