我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
当前回答
基于上面的一些回答,我提出了这个类型安全的函数签名:
export function getStringValuesFromEnum<T>(myEnum: T): (keyof T)[] {
return Object.keys(myEnum).filter(k => typeof (myEnum as any)[k] === 'number') as any;
}
用法:
enum myEnum { entry1, entry2 };
const stringVals = getStringValuesFromEnum(myEnum);
stringVals的类型是'entry1' | 'entry2'
看看它的实际应用
其他回答
我希望这个问题仍然有意义。我使用这样的函数:
function enumKeys(target: Record<string, number|string>): string[] {
const allKeys: string[] = Object.keys(target);
const parsedKeys: string[] = [];
for (const key of allKeys) {
const needToIgnore: boolean
= target[target[key]]?.toString() === key && !isNaN(parseInt(key));
if (!needToIgnore) {
parsedKeys.push(key);
}
}
return parsedKeys;
}
function enumValues(target: Record<string, number|string>): Array<string|number> {
const keys: string[] = enumKeys(target);
const values: Array<string|number> = [];
for (const key of keys) {
values.push(target[key]);
}
return values;
}
例子:
enum HttpStatus {
OK,
INTERNAL_ERROR,
FORBIDDEN = 'FORBIDDEN',
NOT_FOUND = 404,
BAD_GATEWAY = 'bad-gateway'
}
console.log(enumKeys(HttpStatus));
// > ["OK", "INTERNAL_ERROR", "FORBIDDEN", "NOT_FOUND", "BAD_GATEWAY"]
console.log(enumValues(HttpStatus));
// > [0, 1, "FORBIDDEN", 404, "bad-gateway"]
如果你有enum
enum Diet {
KETO = "Ketogenic",
ATKINS = "Atkins",
PALEO = "Paleo",
DGAF = "Whatever"
}
然后你可以得到如下的键和值:
Object.keys(Diet).forEach((d: Diet) => {
console.log(d); // KETO
console.log(Diet[d]) // Ketogenic
});
根据TypeScript文档,我们可以通过Enum和静态函数来实现这一点。
使用静态函数获取Enum名称
enum myEnum {
entry1,
entry2
}
namespace myEnum {
export function GetmyEnumName(m: myEnum) {
return myEnum[m];
}
}
now we can call it like below
myEnum.GetmyEnumName(myEnum.entry1);
// result entry1
要阅读更多关于Enum的静态函数,请点击下面的链接 https://basarat.gitbooks.io/typescript/docs/enums.html
老问题了,为什么不使用const对象映射呢?
不要这样做:
enum Foo {
BAR = 60,
EVERYTHING_IS_TERRIBLE = 80
}
console.log(Object.keys(Foo))
// -> ["60", "80", "BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE", 60, 80]
这样做(注意as const强制转换):
const Foo = {
BAR: 60,
EVERYTHING_IS_TERRIBLE: 80
} as const
console.log(Object.keys(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> [60, 80]
如果你只搜索名称,然后迭代使用:
Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];