简体   繁体   中英

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM