我想将所有枚举值映射到SelectItem数组接口。
selectItem.ts
export interface SelectItem {
label?: string;
value: any;
}
gender.ts
export enum Gender{
Description("MaleDescriptionExample") //?????????
Male = 1,
Description("FemaleDescriptionExample")//?????????
Female = 2
}
我想在下面举例。我写得像C#。但我想要打字稿。我该怎么办?
var myList= selectItem[] ;
this.myList=Gender.map(p=> //?????????
label= p.Description,
value= (int)(p.value)
);
答案 0 :(得分:3)
不能像向C#枚举添加属性那样向枚举添加装饰器。但是,我们可以创建具有与枚举相同的键的类型,这将迫使我们用其字符串描述指定枚举的所有键。
然后,使用该对象,我们只需要获取枚举的键,并在枚举中查找值并在我们的额外对象中查找说明。
export enum Gender {
Male = 1,
Female = 2
}
// We will geta an error if we have missing/ extra or misspelled keys
let descriptions: { [P in keyof typeof Gender]: string } = {
Female: "FemaleDescriptionExample",
Male: "MaleDescriptionExample"
}
export interface SelectItem {
label?: string;
value: any;
}
var myList: SelectItem[] = (Object.keys(Gender) as Array<keyof typeof Gender>)
.filter(p => typeof Gender[p] === "number") // The enum contains both the lookup and the reverse lookup, we only need name->value so we take only the number keys
.map(p => ({
label: descriptions[p],
value: Gender[p]
}));
console.log(myList);