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

6za6bjd0  于 2023-02-13  发布在  TypeScript
关注(0)|答案(2)|浏览(191)

我有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';
    };
}
ep6jt1vc

ep6jt1vc1#

这对你有用吗?

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'
rn0zuynd

rn0zuynd2#

在一个类型的值中使用枚举的惊人方法。

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

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

相关问题