gender.ts
export enum Gender {
Male = 1,
Female = 2
}
export let genderDescriptions: { [P in keyof typeof Gender]: string } = {
Female: "FemaleDescriptionExample",
Male: "MaleDescriptionExample"
}
selectitem.ts
export interface SelectItem {
label?: string;
value: any;
}
my-component.ts
var myList: SelectItem[] = (Object.keys(Gender) as Array<keyof typeof Gender>)
.filter(p => typeof Gender[p] === "number")
.map(p => ({
label: genderDescriptions[p],
value: Gender[p]
}));
console.log(myList);
嗨。我有一个性别枚举,我正在映射到SelectItem数组。控制台给我一个如下结果。运行良好。但是我想要全局enumConverter。所以我写如下,但这是行不通的。我该如何以通用方式做到这一点?
1: {label: "MaleDescriptionExample", value: 1}
2: {label: "FemaleDescriptionExample", value: 2}
我给出了通用参数T和描述,但是到处都出现了错误:
'T'仅指类型,但在此处被用作值
enumToSelectItemArray<T,Description>() {
return (Object.keys(T) as Array<keyof typeof T>)
.filter(p => typeof T[p] === "number" && T[p] !== 3)
.map(p => ({
label: descriptin[p],
value: T[p]
}))
}
答案 0 :(得分:1)
Type参数在运行时会被打字稿删除,因此您无法在运行时通过它们访问任何值。您将需要参数来传递枚举和描述对象。我们将使用通用类型参数使编译器清楚枚举对象和描述对象之间的关系。
KAFKA_CLIENT_CERT
KAFKA_CLIENT_CERT_KEY
KAFKA_TRUSTED_CERT
注意,将映射类型替换为enum Gender {
Male = 1,
Female = 2
}
let genderDescriptions: Record<keyof typeof Gender, string> = {
Female: "FemaleDescriptionExample",
Male: "MaleDescriptionExample"
}
function enumToSelectItemArray<TEnum>(enumObj: TEnum, descriptions: Record<keyof TEnum, string>)
{
return (Object.keys(enumObj) as Array<keyof TEnum>)
.filter(p => typeof enumObj[p] === "number")
.map(p => ({
label: descriptions[p],
value: enumObj[p]
}));
}
console.log(enumToSelectItemArray(Gender, genderDescriptions));
,它们执行相同的操作(它们实际上是相同的操作),并且记录看起来更好,在我之前的回答中忘了它。