Búsqueda de sitios web

javascript - Crear un tipo genérico a partir de enum


Estoy intentando crear un tipo genérico usando enumeraciones.

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

Ahora me gustaría crear un tipo genérico que me ayudara a lograr algo como esto:

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

¿Cómo puedo lograr esto? Gracias

Respuesta #1

Hay una cosa que puedes hacer:

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

No te preocupes, aún puedes usar un enum en lugar de un objeto inmutable.

Artículos relacionados