在界面中使用枚举的 typescript

标签 typescript enums interface

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

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

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 界面中使用 Enum State。这样我就可以使用 STATE.NEWYORKSTATE.BOSTON 枚举。 像这样:

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

感谢阅读。

最佳答案

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

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

请注意,即使您使用了 enum 值,索引器仍然是字符串并且使用了 enum 的值 o。所以这些都是有效的:

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

Demo

关于在界面中使用枚举的 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49819382/

相关文章:

node.js - 枚举的 Mongoose 模型自定义错误消息

c++ - '函数式转换' : illegal as right side of '.' operator

cocoa - Lion 新增的文本选项卡式界面

java - 官方Java教程中的这句话是否不准确?

基于map接口(interface)数组中的key的golang过滤器

node.js - Typescript TS2339 属性不存在

javascript - Angular2 在等待数据加载时更新 View

angular - 我可以使用 distinctUntilKeyChanged 来删除重复的对象吗?

javascript - 使用 typescript@2.0.3 从 "typings"迁移到 "@types"

c# - 如何更新除特定值之外的枚举值