简体   繁体   English

从枚举创建通用类型

[英]Create a Generic Type from enum

I'm trying to create a generic Type using enums.我正在尝试使用枚举创建一个通用类型。

Enum枚举

export enum OverviewSections {
  ALL = 'all',
  SCORE = 'score_breakdown',
  PERFORMANCE = 'performance_over_time',
  ENGAGEMENT = 'engagement',
  COMPANY = 'company_views_graph',
  PEOPLE = 'people_views_graph',
  ARTICLES = 'articles_read_graph',
  PLATFORM = 'platform_sessions_graph',
  EMAILS = 'emails_opened_graph',
}

Now I'd like to create a generic type which would help me achieve something like this:现在我想创建一个通用类型来帮助我实现这样的目标:

Overview: {
    [OverviewSections.ALL]: {
      data: IOverview | null,
      loading: boolean,
      error: boolean
    },
    [OverviewSections.SCORE]: {
      data: IScore | null,
      loading: boolean,
      error: boolean
    },
    [OverviewSections.PERFORMANCE]: {
      data: IPerformace | null,
      loading: boolean,
      error: boolean
    },
    ......
  },

How can I achieve this?我怎样才能做到这一点? Thanks谢谢

There is one thing You can do:你可以做一件事:


// I have replaced ENUM with IMMUTABLE object. It is much safer

const OverviewSections = {
  ALL: 'all',
  SCORE: 'score_breakdown',
  PERFORMANCE: 'performance_over_time',
} as const

// I created type for boilerplate code
type DataStatus<T> = {
  data: T | null
  loading: boolean,
  error: boolean
}

// Mocks for your interfaces
interface IOverview {
  tag: 'IOverview'
}
interface IScore {
  tag: ' IScore'
}
interface IPerformace {
  tag: 'IPerformace'
}

// You still need to map your types
type Mapped = {
  [OverviewSections.ALL]: IOverview;
  [OverviewSections.PERFORMANCE]: IPerformace;
  [OverviewSections.SCORE]: IScore
}

// This type will take all VALUES of OverviewSections,
// because we use them as a keys for our map
type Values<T> = {
  [P in keyof T]: T[P]
}[keyof T]

/**
 * This is the main type
 * 1) It maps through all OverviewSections values
 * 2) Checks if value is equal to Mapped keyof
 * 3) if Yes - create s DataStatus with appropriate generic
 * 4) if No - returns NEVER
 */
type MakeType<E extends Record<string, string>, M> = {
  [P in Values<E>]: P extends keyof M ? DataStatus<M[P]> : never
}

type Result =  MakeType<typeof OverviewSections, Mapped>

Don't worry, You can still use an enum instead of immutable object.别担心,您仍然可以使用enum而不是不可变的 object。

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

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