【问题标题】:Typescript using enum within an interface在接口中使用枚举的打字稿
【发布时间】:2018-09-23 22:54:16
【问题描述】:

我是 Typescript 的新手,我不确定语法。我尝试在线搜索,但没有发现任何有用的信息。

这些是我的接口和枚举定义。

interface Products {
    asian: {[key: string]: string};
    american: {[key: string]: string};
}

enum State {
   NEWYORK = 'nyc',
   BOSTON = 'boston'
}

interface Branch {
   nyc: {
     products: Products;
   };
   boston: {
      products: Products;
   };
}

我不确定如何在Branch 接口中使用枚举State。这样我就可以使用STATE.NEWYORKSTATE.BOSTON 枚举。 像这样的:

interface Branch {
   State.NEWYORK: {
     products: Products;
   };
   STATE.BOSTON: {
      products: Products;
   };
}

感谢阅读。

【问题讨论】:

  • 不确定你的意思..你可以在类型状态的界面中定义一个字段,就像你可以为任何其他类型一样
  • @TitianCernicova-Dragomir 我更新了问题。我对语法感到困惑,我想在 Branch 中使用 Enum 或确保该字段的类型为 Enum nyc: State.NEWYORK

标签: typescript enums interface


【解决方案1】:

您可以使用计算属性的语法:

interface Branch {
   [State.NEWYORK]: {
     products: Products;
   };
   [State.BOSTON]: {
      products: Products;
   };
}

请注意,即使您使用 enum 值,索引器仍然是字符串,并且使用了 enum 的值 o。所以其中任何一个都是有效的:

let f!: Branch;
f[State.NEWYORK]
f["nyc"]
f.nyc

Demo

【讨论】:

  • 使用上述解决方案,我得到一个 TS1169:接口中的计算属性名称必须直接引用内置符号。任何提示如何解决这个问题。
  • @Aniks 你使用的是什么 ts 版本,我没有收到这个错误。
  • 我正在使用“typescript”:“^2.7.2”,我在 IDE 中得到了这个。
【解决方案2】:

通用且无需维护的解决方案:

enum ApiResponseCode {
    SUCCESS = 1,
    FAIL = 2,
    FILE_MODIFIED = 3
};

interface View {
    Enums: {
        ApiResponseCode: {
            [P in keyof typeof ApiResponseCode]: ApiResponseCode;
        }
    }
};

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 2020-01-29
    • 2020-05-09
    • 2020-12-09
    • 2019-12-27
    • 2020-04-30
    • 2021-03-03
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多