简体   繁体   English

是否可以在类型声明中使用枚举的值作为 object 键的值?

[英]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 .我有枚举 HealthPlanStatus ,它是由枚举 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.最后,我想使用枚举的键和值不仅为类型 IHealthPlanResponse生成状态键,而且还生成标题值作为枚举的值。

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 ...):它给了我严格的结构,其中我有一个状态键作为枚举的键( 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:如果您不想在此处看到枚举“键”并希望将string文字作为一种类型,您可以将其更改为:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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