Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在接口中使用枚举的Typescript_Typescript_Enums_Interface - Fatal编程技术网

在接口中使用枚举的Typescript

在接口中使用枚举的Typescript,typescript,enums,interface,Typescript,Enums,Interface,我对Typescript还不熟悉,我不确定它的语法。我试着在网上搜索,但没有找到任何有用的东西 这些是我的接口和枚举定义 interface Products { asian: {[key: string]: string}; american: {[key: string]: string}; } enum State { NEWYORK = 'nyc', BOSTON = 'boston' } interface Branch { nyc: {

我对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;
   };
}
我不知道如何在
分支
界面内使用Enum
State
。这样我就可以使用
STATE.NEWYORK
STATE.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

通用解决方案,无需维护:

枚举ApiResponseCode{
成功=1,
失败=2,
文件\u已修改=3
};
界面视图{
枚举:{
ApiResponseCode:{
[P在ApiResponseCode类型的键中]:ApiResponseCode;
}
}
};

不知道你的意思。。您可以在status类型的接口中定义字段,就像在任何其他类型的接口中一样type@TitianCernicova-德拉戈米尔我更新了问题。我对语法感到困惑,我想在
分支
中使用Enum,或者确保字段的类型为
Enum
nyc:State。纽约
使用上述解决方案,我得到一个TS1169:接口中的计算属性名称必须直接引用内置符号。任何关于如何修复此问题的提示。@Aniks您使用的ts版本是什么,我没有发现此错误。我使用的是“typescript”:“^2.7.2”,我在IDE中获得此错误。