我想迭代一个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"
}
你张贴的代码将工作;它将打印出枚举的所有成员,包括枚举成员的值。例如,以下代码:
enum myEnum { bar, foo }
for (var enumMember in myEnum) {
console.log("enum member: ", enumMember);
}
将打印以下内容:
Enum member: 0
Enum member: 1
Enum member: bar
Enum member: foo
如果你只想要成员名,而不是值,你可以这样做:
for (var enumMember in myEnum) {
var isValueProperty = Number(enumMember) >= 0
if (isValueProperty) {
console.log("enum member: ", myEnum[enumMember]);
}
}
只打印出名字:
Enum member: bar
Enum member: foo
注意:这有点依赖于实现细节:TypeScript将enum编译为JS对象,enum值是对象的成员。如果TS决定在未来以不同的方式实现它们,上述技术可能会中断。
假设您坚持使用规则,只生成带有数值的枚举,您可以使用这段代码。这正确地处理了名称恰好是有效数字的情况
enum Color {
Red,
Green,
Blue,
"10" // wat
}
var names: string[] = [];
for(var n in Color) {
if(typeof Color[n] === 'number') names.push(n);
}
console.log(names); // ['Red', 'Green', 'Blue', '10']
在当前的TypeScript版本1.8.9中,我使用类型化enum:
export enum Option {
OPTION1 = <any>'this is option 1',
OPTION2 = <any>'this is option 2'
}
与结果在这个Javascript对象:
Option = {
"OPTION1": "this is option 1",
"OPTION2": "this is option 2",
"this is option 1": "OPTION1",
"this is option 2": "OPTION2"
}
所以我必须通过键和值查询,只返回值:
let optionNames: Array<any> = [];
for (let enumValue in Option) {
let optionNameLength = optionNames.length;
if (optionNameLength === 0) {
this.optionNames.push([enumValue, Option[enumValue]]);
} else {
if (this.optionNames[optionNameLength - 1][1] !== enumValue) {
this.optionNames.push([enumValue, Option[enumValue]]);
}
}
}
我在数组中收到选项键:
optionNames = [ "OPTION1", "OPTION2" ];
当我遇到同样的问题时,你可以使用我写的enum-values包:
Git: enum-values
var names = EnumValues.getNames(myEnum);
我发现这个解决方案更优雅:
for (let val in myEnum ) {
if ( isNaN( parseInt( val )) )
console.log( val );
}
它显示:
bar
foo
对我来说,一个更简单、实用和直接的方法来理解正在发生的事情,就是下面的列举:
enum colors { red, green, blue };
本质上将转换为:
var colors = { red: 0, green: 1, blue: 2,
[0]: "red", [1]: "green", [2]: "blue" }
正因为如此,以下情况将是正确的:
colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0
这创建了一个简单的方法来获取枚举的名称,如下所示:
var color: colors = colors.red;
console.log("The color selected is " + colors[color]);
它还创建了一种将字符串转换为枚举值的好方法。
var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];
以上两种情况更为常见,因为通常您对特定值的名称和以通用方式序列化值更感兴趣。
虽然答案已经提供了,但几乎没有人指向文档
下面是一个片段
enum Enum {
A
}
let nameOfA = Enum[Enum.A]; // "A"
请记住,string enum成员根本不会生成反向映射。
如果你只搜索名称,然后迭代使用:
Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];
这个解决方案也可以。
enum ScreenType {
Edit = 1,
New = 2,
View = 4
}
var type: ScreenType = ScreenType.Edit;
console.log(ScreenType[type]); //Edit
唯一的解决方案,适用于我在所有情况下(即使值是字符串)是以下:
var enumToString = function(enumType, enumValue) {
for (var enumMember in enumType) {
if (enumType[enumMember]==enumValue) return enumMember
}
}
从TypeScript 2.4开始,枚举不再包含键作为成员。来源TypeScript自述文件
需要注意的是,字符串初始化的枚举不能反向映射到原始枚举成员名。换句话说,你不能写Colors["RED"]来获得字符串"RED"。
我的解决方案:
export const getColourKey = (value: string ) => {
let colourKey = '';
for (const key in ColourEnum) {
if (value === ColourEnum[key]) {
colourKey = key;
break;
}
}
return colourKey;
};
让ts-enum-util (github, npm)为您工作,并提供许多额外的类型安全实用程序。适用于字符串和数字enum,正确忽略数字enum的数字索引反向查找条目:
字符串枚举:
import {$enum} from "ts-enum-util";
enum Option {
OPTION1 = 'this is option 1',
OPTION2 = 'this is option 2'
}
// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();
// type: Option[]
// value: ["this is option 1", "this is option 2"]
const values = $enum(Option).getValues();
数字枚举:
enum Option {
OPTION1,
OPTION2
}
// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();
// type: Option[]
// value: [0, 1]
const values = $enum(Option).getValues();
基于上面的一些回答,我提出了这个类型安全的函数签名:
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'
看看它的实际应用
从TypeScript 2.4开始,枚举可以包含字符串初始化器https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html
这允许你这样写:
enum Order {
ONE = "First",
TWO = "Second"
}
console.log(`One is ${Order.ONE.toString()}`);
得到这样的输出:
一个是First
根据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
我的Enum是这样的:
export enum UserSorting {
SortByFullName = "Sort by FullName",
SortByLastname = "Sort by Lastame",
SortByEmail = "Sort by Email",
SortByRoleName = "Sort by Role",
SortByCreatedAt = "Sort by Creation date",
SortByCreatedBy = "Sort by Author",
SortByUpdatedAt = "Sort by Edit date",
SortByUpdatedBy = "Sort by Editor",
}
这样做会返回undefined:
UserSorting[UserSorting.SortByUpdatedAt]
为了解决这个问题,我选择了另一种使用管道的方法:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'enumKey'
})
export class EnumKeyPipe implements PipeTransform {
transform(value, args: string[] = null): any {
let enumValue = args[0];
var keys = Object.keys(value);
var values = Object.values(value);
for (var i = 0; i < keys.length; i++) {
if (values[i] == enumValue) {
return keys[i];
}
}
return null;
}
}
要使用它:
return this.enumKeyPipe.transform(UserSorting, [UserSorting.SortByUpdatedAt]);
这不是你问题的确切答案,但它是解决你问题的一个技巧。
export module Gender {
export enum Type {
Female = 1,
Male = 2
};
export const List = Object.freeze([
Type[Type.Female] ,
Type[Type.Male]
]);
}
您可以以自己想要的方式扩展列表模型。
export const List = Object.freeze([
{ name: Type[Type.Female], value: Type.Female } ,
{ name: Type[Type.Male], value: Type.Male }
]);
现在,你可以这样使用它:
for(const gender of Gender.List){
console.log(gender.name);
console.log(gender.value);
}
or:
if(i === Gender.Type.Male){
console.log("I am a man.");
}
我写了一个EnumUtil类,它通过枚举值进行类型检查:
export class EnumUtils {
/**
* Returns the enum keys
* @param enumObj enum object
* @param enumType the enum type
*/
static getEnumKeys(enumObj: any, enumType: EnumType): any[] {
return EnumUtils.getEnumValues(enumObj, enumType).map(value => enumObj[value]);
}
/**
* Returns the enum values
* @param enumObj enum object
* @param enumType the enum type
*/
static getEnumValues(enumObj: any, enumType: EnumType): any[] {
return Object.keys(enumObj).filter(key => typeof enumObj[key] === enumType);
}
}
export enum EnumType {
Number = 'number',
String = 'string'
}
如何使用:
enum NumberValueEnum{
A= 0,
B= 1
}
enum StringValueEnum{
A= 'A',
B= 'B'
}
EnumUtils.getEnumKeys(NumberValueEnum, EnumType.Number);
EnumUtils.getEnumValues(NumberValueEnum, EnumType.Number);
EnumUtils.getEnumKeys(StringValueEnum, EnumType.String);
EnumUtils.getEnumValues(StringValueEnum, EnumType.String);
NumberValueEnum键的结果:["A", "B"]
NumberValueEnum值的结果:[0,1]
StringValueEnumkeys的结果:["A", "B"]
StringValueEnumvalues的结果:["A", "B"]
这里发现的另一个有趣的解决方案是使用ES6 Map:
export enum Type {
low,
mid,
high
}
export const TypeLabel = new Map<number, string>([
[Type.low, 'Low Season'],
[Type.mid, 'Mid Season'],
[Type.high, 'High Season']
]);
USE
console.log(TypeLabel.get(Type.low)); // Low Season
TypeLabel.forEach((label, value) => {
console.log(label, value);
});
// Low Season 0
// Mid Season 1
// High Season 2
我通过搜索“TypeScript iterate over enum keys”找到了这个问题。所以我只想给出对我来说有用的解。也许对别人也有帮助。
我的情况如下:我想在每个枚举键上迭代,然后过滤一些键,然后访问一些对象,其中键作为枚举的计算值。这就是没有TS误差的方法。
enum MyEnum = { ONE = 'ONE', TWO = 'TWO' }
const LABELS = {
[MyEnum.ONE]: 'Label one',
[MyEnum.TWO]: 'Label two'
}
// to declare type is important - otherwise TS complains on LABELS[type]
// also, if replace Object.values with Object.keys -
// - TS blames wrong types here: "string[] is not assignable to MyEnum[]"
const allKeys: Array<MyEnum> = Object.values(MyEnum)
const allowedKeys = allKeys.filter(
(type) => type !== MyEnum.ONE
)
const allowedLabels = allowedKeys.map((type) => ({
label: LABELS[type]
}))
老问题了,为什么不使用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]
我写了一个helper函数来枚举一个枚举:
static getEnumValues<T extends number>(enumType: {}): T[] {
const values: T[] = [];
const keys = Object.keys(enumType);
for (const key of keys.slice(0, keys.length / 2)) {
values.push(<T>+key);
}
return values;
}
用法:
for (const enumValue of getEnumValues<myEnum>(myEnum)) {
// do the thing
}
该函数返回可以轻松枚举的内容,并将其转换为枚举类型。
如果你有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 STATES {
LOGIN,
LOGOUT,
}
export const enumToRecordWithKeys = <E extends any>(enumeration: E): E => (
Object.keys(enumeration)
.filter(key => typeof enumeration[key] === 'number')
.reduce((record, key) => ({...record, [key]: key }), {}) as E
);
export const enumToRecordWithValues = <E extends any>(enumeration: E): E => (
Object.keys(enumeration)
.filter(key => typeof enumeration[key] === 'number')
.reduce((record, key) => ({...record, [key]: enumeration[key] }), {}) as E
);
const states = enumToRecordWithKeys(STATES)
const statesWithIndex = enumToRecordWithValues(STATES)
console.log(JSON.stringify({
STATES,
states,
statesWithIndex,
}, null ,2));
// Console output:
{
"STATES": {
"0": "LOGIN",
"1": "LOGOUT",
"LOGIN": 0,
"LOGOUT": 1
},
"states": {
"LOGIN": "LOGIN",
"LOGOUT": "LOGOUT"
},
"statesWithIndex": {
"LOGIN": 0,
"LOGOUT": 1
}
}
这里的答案似乎都不能在严格模式下使用string-enum。
考虑enum为:
enum AnimalEnum {
dog = "dog", cat = "cat", mouse = "mouse"
}
使用AnimalEnum["dog"]访问可能会导致如下错误:
元素隐式具有“any”类型,因为类型“any”的表达式不能用于索引类型“typeof AnimalEnum”.ts(7053)。
这种情况下的正确解,写为:
AnimalEnum["dog" as keyof typeof AnimalEnum]
要获得枚举值的列表,您必须使用:
enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}
Object.values(AnimalEnum);
这里有很多答案,尽管这是一个7年前的问题,但我还是查了一下,我猜会有更多的答案出现在这里。这是我的解决方案,它比其他解决方案简单一点,它处理数字/文本/混合值枚举,都是一样的。
enum funky {
yum , tum='tum', gum = 'jump', plum = 4
}
const list1 = Object.keys(funky)
.filter(k => (Number(k).toString() === Number.NaN.toString()));
console.log(JSON.stringify(list1)); // ["yum","tum","gum","plum"]"
// for the numeric enum vals (like yum = 0, plum = 4), typescript adds val = key implicitly (0 = yum, 4 = plum)
// hence we need to filter out such numeric keys (0 or 4)
简单地说
如果你的枚举如下:
export enum Colors1 {
Red = 1,
Green = 2,
Blue = 3
}
要获得特定的文本和值:
console.log(Colors1.Red); // 1
console.log(Colors1[Colors1.Red]); // Red
获取值和文本列表:
public getTextAndValues(e: { [s: number]: string }) {
for (const enumMember in e) {
if (parseInt(enumMember, 10) >= 0) {
console.log(e[enumMember]) // Value, such as 1,2,3
console.log(parseInt(enumMember, 10)) // Text, such as Red,Green,Blue
}
}
}
this.getTextAndValues(Colors1)
如果你的枚举如下:
export enum Colors2 {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
要获得特定的文本和值:
console.log(Colors2.Red); // Red
console.log(Colors2["Red"]); // Red
获取值和文本列表:
public getTextAndValues(e: { [s: string]: string }) {
for (const enumMember in e) {
console.log(e[enumMember]);// Value, such as Red,Green,Blue
console.log(enumMember); // Text, such as Red,Green,Blue
}
}
this.getTextAndValues(Colors2)
我希望这个问题仍然有意义。我使用这样的函数:
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"]
我看不正确的答案看累了,就自己做了。
这个有测试。 适用于所有类型的枚举。 正确地输入。
type EnumKeys<Enum> = Exclude<keyof Enum, number>
const enumObject = <Enum extends Record<string, number | string>>(e: Enum) => {
const copy = {...e} as { [K in EnumKeys<Enum>]: Enum[K] };
Object.values(e).forEach(value => typeof value === 'number' && delete copy[value]);
return copy;
};
const enumKeys = <Enum extends Record<string, number | string>>(e: Enum) => {
return Object.keys(enumObject(e)) as EnumKeys<Enum>[];
};
const enumValues = <Enum extends Record<string, number | string>>(e: Enum) => {
return [...new Set(Object.values(enumObject(e)))] as Enum[EnumKeys<Enum>][];
};
enum Test1 { A = "C", B = "D"}
enum Test2 { A, B }
enum Test3 { A = 0, B = "C" }
enum Test4 { A = "0", B = "C" }
enum Test5 { undefined = "A" }
enum Test6 { A = "undefined" }
enum Test7 { A, B = "A" }
enum Test8 { A = "A", B = "A" }
enum Test9 { A = "B", B = "A" }
console.log(enumObject(Test1)); // {A: "C", B: "D"}
console.log(enumObject(Test2)); // {A: 0, B: 1}
console.log(enumObject(Test3)); // {A: 0, B: "C"}
console.log(enumObject(Test4)); // {A: "0", B: "C"}
console.log(enumObject(Test5)); // {undefined: "A"}
console.log(enumObject(Test6)); // {A: "undefined"}
console.log(enumObject(Test7)); // {A: 0,B: "A"}
console.log(enumObject(Test8)); // {A: "A", B: "A"}
console.log(enumObject(Test9)); // {A: "B", B: "A"}
console.log(enumKeys(Test1)); // ["A", "B"]
console.log(enumKeys(Test2)); // ["A", "B"]
console.log(enumKeys(Test3)); // ["A", "B"]
console.log(enumKeys(Test4)); // ["A", "B"]
console.log(enumKeys(Test5)); // ["undefined"]
console.log(enumKeys(Test6)); // ["A"]
console.log(enumKeys(Test7)); // ["A", "B"]
console.log(enumKeys(Test8)); // ["A", "B"]
console.log(enumKeys(Test9)); // ["A", "B"]
console.log(enumValues(Test1)); // ["C", "D"]
console.log(enumValues(Test2)); // [0, 1]
console.log(enumValues(Test3)); // [0, "C"]
console.log(enumValues(Test4)); // ["0", "C"]
console.log(enumValues(Test5)); // ["A"]
console.log(enumValues(Test6)); // ["undefined"]
console.log(enumValues(Test7)); // [0, "A"]
console.log(enumValues(Test8)); // ["A"]
console.log(enumValues(Test9)); // ["B", "A"]
在线版本。
如果它是你的枚举,你定义如下所示,名称和值是相同的,它会直接给你条目的名称。
enum myEnum {
entry1="entry1",
entry2="entry2"
}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
这对于基于键值的enum更有效:
enum yourEnum {
["First Key"] = "firstWordValue",
["Second Key"] = "secondWordValue"
}
Object.keys(yourEnum)[Object.values(yourEnum).findIndex(x => x === yourValue)]
// Result for passing values as yourValue
// FirstKey
// SecondKey
你可以用下面的方法从Enum中获取一个名称数组:
const enumNames: string[] = Object.keys(YourEnum).filter(key => isNaN(Number(key)));
他们在官方文件中提供了一个叫做“反向映射”的概念。它帮助了我:
https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
解决方法很简单:
enum Enum {
A,
}
let a = Enum.A;
let nameOfA = Enum[a]; // "A"
假设您有一个枚举
export enum SCROLL_LABEL_OFFSET {
SMALL = 48,
REGULAR = 60,
LARGE = 112
}
你想要创建一个基于枚举的类型而不仅仅是复制和粘贴。 你可以像这样使用枚举来创建你的类型:
export type ScrollLabelOffset = keyof typeof SCROLL_LABEL_OFFSET;
结果你会收到一个可能值为'SMALL' | 'REGULAR' | 'LARGE'的类型
可以是简短的:
enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}
Object.keys(AnimalEnum).filter(v => typeof v == 'string' && isNaN(v))
在TypeScript中,一个enum在javascript中被编译成一个map(从键中获取值):
enum MyEnum {
entry0,
entry1,
}
console.log(MyEnum['entry0']); // 0
console.log(MyEnum['entry1']); // 1
它还创建了一个反向映射(从值中获取键):
console.log(MyEnum[0]); // 'entry0'
console.log(MyEnum[0]); // 'entry1'
所以你可以通过以下方式访问一个条目的名称:
console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'
但是,string enum在设计上没有反向映射(参见注释和pull request),因为这可能导致映射对象中的键和值之间的冲突。
enum MyEnum {
entry0 = 'value0',
entry1 = 'value1',
}
console.log(MyEnum['value0']); // undefined
console.log(MyEnum['value1']); // undefined
如果你想强制你的字符串enum编译一个反向映射(你必须确保所有的键和值都是不同的),你可以使用这个技巧:
enum MyEnum {
entry0 = <any>'value0',
entry1 = <any>'value1',
}
console.log(MyEnum['value0']); // 'entry0'
console.log(MyEnum['value1']); // 'entry1'
console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'
具有数字enum:
enum MyNumericEnum {
First = 1,
Second = 2
}
你需要先把它转换成数组:
const values = Object.values(MyNumericEnum);
// ['First', 'Second', 1, 2]
如您所见,它同时包含键和值。钥匙先放。
之后,你可以检索它的键:
values.slice(0, values.length / 2);
// ['First', 'Second']
和值:
values.slice(values.length / 2);
// [1, 2]
对于字符串enum,你可以使用Object.keys(MyStringEnum)来分别获取key和Object.values(MyStringEnum)来分别获取值。
尽管提取混合枚举的键和值有点挑战性。
你可以这样做,我认为这是最短、最干净、最快的:
Object.entries(test).filter(([key]) => (!~~key && key !== "0"))
给定以下混合类型枚举定义:
enum testEnum {
Critical = "critical",
Major = 3,
Normal = "2",
Minor = "minor",
Info = "info",
Debug = 0
};
它将会变成以下内容:
var testEnum = { 关键:“至关重要的”, 主要:3, 正常:“2”, 小:“小”, 信息:“信息”, 调试:0, [0]:“关键”, [1]: 3, [2]:“2”, [3]:“小”, [4]:“信息”, [5]: 0 } 函数safeEnumEntries(test) { return Object.entries(test).filter(([key]) => (!~~key && key !== "0"); }; console.log (safeEnumEntries (testEnum));
执行函数后,你只会得到好的条目:
[
["Critical", "critical"],
["Major", 3],
["Normal", "2"],
["Minor", "minor"],
["Info", "info"],
["Debug", 0]
]
我卑微的2美分基于阅读一个了不起的评论从github TS讨论
const EnvironmentVariants = ['development', 'production', 'test'] as const
type EPredefinedEnvironment = typeof EnvironmentVariants[number]
然后在编译时:
// TS2322: Type '"qaEnv"' is not assignable to type '"development" | "production" | "test"'.
const qaEnv: EPredefinedEnvironment = 'qa'
在运行时:
function isPredefinedEnvironemt(env: string) {
for (const predefined of EnvironmentVariants) {
if (predefined === env) {
return true
}
}
return false
}
assert(isPredefinedEnvironemet('test'), true)
assert(isPredefinedEnvironemet('qa'), false)
注意,for(const index in environmentvariables){…}将遍历"0","1","2"集合
Typescript游乐场示例
enum TransactionStatus {
SUBMITTED = 'submitted',
APPROVED = 'approved',
PAID = 'paid',
CANCELLED = 'cancelled',
DECLINED = 'declined',
PROCESSING = 'processing',
}
let set1 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.SUBMITTED || value === TransactionStatus.CANCELLED).map(([key,]) => {
return key
})
let set2 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.PAID || value === TransactionStatus.APPROVED).map(([key,]) => {
return key
})
let allKeys = Object.keys(TransactionStatus)
console.log({set1,set2,allKeys})
如果你想在html中获取名字
对于这个枚举
enum CanadianProvinces {
AB,
BC,
MB,
NB,
NL,
NT,
NS,
NU,
ON,
PE,
QC,
SK,
YT
}
将组件中的变量赋值为
canadianProvinces = CanadianProvinces
然后,在你的html
{{canadianProvinces[0]}}