Ani*_*iks 6 enums interface typescript
我是 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;
};
}
Run Code Online (Sandbox Code Playgroud)
我不确定如何使用 EnumState内部Branch接口。这样我就可以使用STATE.NEWYORKand STATE.BOSTONEnums。像这样的东西:
interface Branch {
State.NEWYORK: {
products: Products;
};
STATE.BOSTON: {
products: Products;
};
}
Run Code Online (Sandbox Code Playgroud)
谢谢阅读。
您可以使用计算属性的语法:
interface Branch {
[State.NEWYORK]: {
products: Products;
};
[State.BOSTON]: {
products: Products;
};
}
Run Code Online (Sandbox Code Playgroud)
请注意,即使您使用这些值,索引器仍然是字符串,并且使用的enum值 o 。enum因此,其中任何一个都是有效的:
let f!: Branch;
f[State.NEWYORK]
f["nyc"]
f.nyc
Run Code Online (Sandbox Code Playgroud)