2

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

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Hello. Is there any way to get the same structure but using intefraces instead of type?
1

Amazing approach to use enum in one of type's value.

export enum selectedYearTypeValues {
    'currentYear',
    'All'
}

type Props = {
    selectedYear: keyof typeof selectedYearTypeValues;
    setSelectedYear: (value: keyof typeof selectedYearTypeValues) => void;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.