Ole
Ole

Reputation: 46978

Mapping Typescript Enums by their keys without using a Map?

Have the following Enum instances:

export enum TopicCategories {
    GUIDES = 'Guides',
    TASKS = 'Tasks',
    CONCEPTS = 'Concepts',
    FORMULAS = 'Formulas',
    BLOGS = 'Blogs'
}

export enum TopicTypes {
    GUIDES = 'guide',
    TASK = 'task',
    CONCEPT = 'concept',
    FORMULA = 'formula',
    BLOG = 'blog'
}

export const topicCategoryToTopicTypeMap:Map<TopicCategories, TopicTypes> = new Map();

topicCategoryToTopicTypeMap.set(TopicCategories.BLOGS, TopicTypes.BLOG);

The topicCategoryToTopicTypeMap:Map instance will allow me to get the TopicType.BLOG using the TopicCategory.BLOG as a key value.

Is there a way to do this directly using only the Enum instances. In other words is it possible to eliminate the Map instance and perform the mapping directly?

Upvotes: 1

Views: 42

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138277

  const categoryToTopic = { "Guides" : "guide", /*...*/ };

  type TopicCategories = keyof typeof categoryToTopic;
  type TopicTypes = (typeof categoryToTopic)[TopicCategories];

Not quite. enums only work well with primitives, therefore you can't directly store more data on the enums.

Upvotes: 1

Related Questions