TypeScriptのEnum型のreverse mapをつくる
JavaScriptの文法
['foo' => 'bar']なTypeScriptのEnumがあったときに、['bar' => 'foo']なmapを作りたい
文字列のEnumのreverse mapping存在しないことが仕様なので、自分で作る必要がある
/tasuwo/TypeScript における enum の reverse mapping
https://www.typescriptlang.org/docs/handbook/enums.html#enums-at-runtime
Keep in mind that string enum members do not get a reverse mapping generated at all.
charactorやnumberはいける
code:enum.ts
enum Enum {
A, // charactor enum
}
let a = Enum.A;
let nameOfA = Enuma; // "A"
https://www.typescriptlang.org/docs/handbook/enums.html#enums-at-runtime
文字列に対するreverse mappingをつくる
Mapオブジェクトででやるならこんな感じ?
code:ts
const createMap = (): Map<string, string> => {
const reverseMap = new Map<string, string>();
Object.entries(Enum).forEach(
(key, value) => {
reverseMap.set(value, key);
}
);
return reverseMap
}
javascript - TypeScript enum to object array - Stack Overflow
2019/1/21 https://stackoverflow.com/questions/54297376/getting-the-enum-key-with-the-value-string-reverse-mapping-in-typescript
TypeScript: Documentation - TypeScript 2.9
keyof typeof
objectに対するreversemap
https://stackoverflow.com/questions/49285864/is-there-a-valueof-similar-to-keyof-in-typescript