从枚举创建通用类型 [英] Create a Generic Type from enum
本文介绍了从枚举创建通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用枚举创建一个泛型类型.
I'm trying to create a generic Type using enums.
枚举
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
推荐答案
你可以做一件事:
// 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
而不是不可变对象.
Don't worry, You can still use an enum
instead of immutable object.
这篇关于从枚举创建通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文