我是 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.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
关于在界面中使用枚举的 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49819382/