简体   繁体   English

使用字符串枚举作为Map键

[英]Using string enum as Map keys

I'd like to use a TypeScript enum with string values as Map key: 我想使用带有字符串值的TypeScript enum作为Map键:

enum Type {
    a = 'value_a',
    b = 'value_b'
}

const values = new Map<Type, number>();

// set a single value
values.set(Type.a, 1);

This works fine. 这很好。 I can only set keys as defined in the enum. 我只能设置枚举中定义的键。 Now I'd like to fill the map, and set values for all entries in the Type enum: 现在,我想填充地图,并为Type枚举中的所有条目设置值:

// trying to set all values
for (const t in Type) {
  values.set(Type[t], 0); // error
}

This however gives my compile error “Argument of type 'string' is not assignable to parameter of type 'Type'.” 但是,这给了我编译错误“类型为'string'的参数不能分配给类型为'Type'的参数。”

What would be the recommended solution here? 这里推荐的解决方案是什么? Doing a values.set(Type[t] as Type, 0); 做一个values.set(Type[t] as Type, 0); does the trick, but I'm sure there must be a more elegant solution? 绝招,但我确定必须有一个更优雅的解决方案?

Code in TypeScript Playground TypeScript Playground中的代码

Use union types instead of enums. 使用联合类型而不是枚举。

type Type = 'value_a' | 'value_b';
const TYPES: Type[] = ['value_a', 'value_b'];

The bad thing is, that it is little code duplication. 不好的是,它很少重复代码。

The good thing is, that it's simple and you won't encounter unexpected behavior. 好消息是,它很简单,而且您不会遇到意外的行为。 At the end of the day, you won't mind little code duplication. 归根结底,您不会在乎很少的代码重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM