![](/img/trans.png)
[英]Typescript: How to use key type as enum in an object keep all enum values as optional?
[英]Is it possible to use enum's values as value for object key in type declaration?
我有枚舉 HealthPlanStatus ,它是由枚舉 HealthPlanStatus生成的。 最后,我想使用枚舉的鍵和值不僅為類型 IHealthPlanResponse生成狀態鍵,而且還生成標題值作為枚舉的值。
export enum HealthPlanStatus {
Todo = 'To-Do',
InProgress = 'Working on it',
}
export type IHealthPlanResponse = {
[status in keyof typeof HealthPlanStatus]: {
title: string;
};
};
它給了我嚴格的結構,其中我有一個狀態鍵作為枚舉的鍵( Todo、InProgress ...):
type IHealthPlanResponse = {
readonly Todo: {
title: string;
};
readonly InProgress: {
title: string;
};
}
我也想有一個標題類型作為枚舉的值。 例如:
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
如果您不想在此處看到枚舉“鍵”並希望將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.