[英]Typescript using enum within an interface
我是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
接口中使用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
值,索引器仍是字符串和值为0,中enum
使用。 所以这些都是有效的:
let f!: Branch;
f[State.NEWYORK]
f["nyc"]
f.nyc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.