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

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

我有 enum HealthPlanStatus,它是由 enum HealthPlanStatus 生成的。最后,我想使用枚举的键和值不仅为 type IHealthPlanResponse 生成 status 键,而且还生成 title 作为枚举值的值。

export enum HealthPlanStatus {
    Todo = 'To-Do',
    InProgress = 'Working on it',
}
export type IHealthPlanResponse = {
    [status in keyof typeof HealthPlanStatus]: {
        title: string;
    };
};

它给了我严格的结构,我有一个 status 键作为枚举的键(Todo,InProgress...):

type IHealthPlanResponse = {
    readonly Todo: {
        title: string;
    };
    readonly InProgress: {
        title: string;
    };
}

我还想要一个 title 类型作为枚举值。 例如:

 type IHealthPlanResponse = {
    readonly Todo: {
        title: 'To-Do';
    };
    readonly InProgress: {
        title: 'Working on it';
    };
}

这对你有用吗?

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

如果您不想在此处看到枚举 'key' 并希望将 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'