从枚举创建泛型

Create a Generic Type from 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',
}

现在我想创建一个通用类型来帮助我实现这样的目标:

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
    },
    ......
  },

我怎样才能做到这一点?谢谢

您可以做一件事:


// 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>

别担心,您仍然可以使用 enum 而不是不可变对象。