gpt4 book ai didi

typescript - 从 typescript 中的值获取枚举的键

转载 作者:行者123 更新时间:2023-12-03 08:54:48 34 4
gpt4 key购买 nike

我有以下枚举

export enum Operators {
Equal = "1",
NotEqual = "2",
GreatherOrEqual = "3",
LessOrEqual = "4",
Contains = "5",
Null = "6",
NotNull = "7",
Between = "8",
StartsWith = "9",
EndsWith = "10"
}

我需要从存储的值中恢复枚举键。我创建了以下内容:

GetEnumTextByValue ( valueOperator: string ): string {
const values: string[] = Object.values( Operators ).filter( v => v == v );
const keys: string[] = Object.keys( Operators ).filter( k => k == k );
const index: number = values.indexOf( valueOperator );
return keys[ index ];
}

该函数返回我需要的内容,但是有没有更简单的方法来获取 key ?

最佳答案

我将此函数用于任何枚举

export function getEnumKeyByEnumValue(myEnum: any, enumValue: number | string): string {
let keys = Object.keys(myEnum).filter((x) => myEnum[x] == enumValue);
return keys.length > 0 ? keys[0] : '';
}

使用 jest 进行测试

describe('enum', () => {
enum TestEnumWithNumber {
ZERO
}

enum TestEnumWithString {
ZERO = 'ZERO'
}

it('should return correct key when enum has number values', function () {
const key = getEnumKeyByEnumValue(TestEnumWithNumber, TestEnumWithNumber.ZERO);
expect(key).toBe('ZERO');
});

it('should return correct key when enum has string values', function () {
const key = getEnumKeyByEnumValue(TestEnumWithString, TestEnumWithString.ZERO);
expect(key).toBe('ZERO');
});
});

关于typescript - 从 typescript 中的值获取枚举的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56263980/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com