Vyacheslav Tarshevskiy
Vyacheslav Tarshevskiy

Reputation: 107

Is it possible to use enum's values as value for object key in type declaration?

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

Upvotes: 2

Views: 2939

Answers (2)

Muhammad Rafeh Atique
Muhammad Rafeh Atique

Reputation: 872

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

Upvotes: 1

Tobias S.
Tobias S.

Reputation: 23855

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'

Upvotes: 1

Related Questions