I have enum HealthPlanStatus which was generated by enum HealthPlanStatus. In the end I would like to use enum's keys and values to generate not only status keys for type IHealthPlanResponse but also a title value as enum's values.
export enum HealthPlanStatus {
Todo = 'To-Do',
InProgress = 'Working on it',
}
export type IHealthPlanResponse = {
[status in keyof typeof HealthPlanStatus]: {
title: string;
};
};
It gives me strict structure where I have a status key as enum's key (Todo, InProgress...):
type IHealthPlanResponse = {
readonly Todo: {
title: string;
};
readonly InProgress: {
title: string;
};
}
Also I would like to have a title type as enum's values. For example:
type IHealthPlanResponse = {
readonly Todo: {
title: 'To-Do';
};
readonly InProgress: {
title: 'Working on it';
};
}
CodePudding user response:
Does this work for you?
export enum HealthPlanStatus {
Todo = 'To-Do',
InProgress = 'Working on it',
}
export type IHealthPlanResponse = {
readonly [status in keyof typeof HealthPlanStatus]: {
title: (typeof HealthPlanStatus)[status];
};
};
let t: IHealthPlanResponse = {} as any
const status = t.InProgress.title // -> HealthPlanStatus.InProgress
If you don't like to see the enum 'key' here and want to have the string
literal as a type you can change it to this:
export type IHealthPlanResponse = {
readonly [status in keyof typeof HealthPlanStatus]: {
title: `${(typeof HealthPlanStatus)[status]}`;
};
};
let t: IHealthPlanResponse = {} as any
const status = t.InProgress.title // -> 'Working on it'