考虑以下枚举:
export const SOME_STRING_ENUM {
ONE = 'one',
TWO = 'two'
}
现在让我们假设,我需要一些值映射器到这个枚举,我想出了这样一个怪物:
export type eKey = keyof typeof SOME_STRING_ENUM;
export const mapper: {[k in eKey]?: string} = {
[SOME_STRING_ENUM[SOME_STRING_ENUM.ONE]]: 'This is label for one'
[SOME_STRING_ENUM[SOME_STRING_ENUM.TWO]]: 'This is label for two'
}
// please note referring to labels via [E[E.K]] not via just plain E.K
结束然后获得那些映射器键更可笑的是磨练:
public mapEnum(reason: SOME_STRING_ENUM) {
return mapper[SOME_STRING_ENUM[reason]];
}
嗯……上面效果很好。但这太丑陋了,我不完全相信我哪里出错了,以至于我需要使用双重引用来让自己对按标签引用对象感到满意......我预期的解决方案将非常简单:
export type eKey = keyof typeof SOME_STRING_ENUM;
export const mapper: {[k in eKey]?: string} = {
[SOME_STRING_ENUM.ONE]: 'This is label for one'
[SOME_STRING_ENUM.TWO]: 'This is label for two'
}
public mapEnum(reason: SOME_STRING_ENUM) {
return mapper[reason];
}
这可以用字符串枚举器实现吗?还是像往常一样,一开始我会感到困惑?
谢谢你的帮助!
您可以改为使用枚举的值,而不是您在此处使用的键。
为此,您可以通过T[keyof T]
-T
您的枚举类型 ( typeof SOME_STRING_ENUM
)在哪里提取对象值。
这与您编写的第二个示例非常相似:
export enum SOME_STRING_ENUM {
ONE = 'one',
TWO = 'two'
}
export type eKey = typeof SOME_STRING_ENUM[keyof typeof SOME_STRING_ENUM];
export const mapper: { [k in eKey]: string } = {
[SOME_STRING_ENUM.ONE]: 'This is label for one',
[SOME_STRING_ENUM.TWO]: 'This is label for two',
}
function mapEnum(reason: SOME_STRING_ENUM) {
return mapper[reason];
}
游乐场链接在这里
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句