[英]How to create an enum with typescript and returning string
guys i wanna ask if i can create an enum that looks like this 伙计们,我想问问我是否可以创建一个像这样的枚举
export enum CompanyMemberTypeEnum {
DIRECTORS,
SHAREHOLDERS,
DIRECTORS_AND_SHAREHOLDERS
}
CompanyMemberTypeEnum.DIRECTORS
will return 0 right ? CompanyMemberTypeEnum.DIRECTORS
将返回0,对吗? but how if i want to create a function that can get string of an enum like this 但是如果我想创建一个可以获取像这样的枚举的字符串的函数
CompanyMemberTypeEnum.getList(CompanyMemberTypeEnum.DIRECTORS)
will return 'Directors' 将返回“导演”
in a enum file, is that possible ? 在枚举文件中,这可能吗?
Prior to TypeScript 2.4
, TypeScript only supported number-based enums, but nowadays it is possible out of the box. 在
TypeScript 2.4
之前,TypeScript仅支持基于数字的枚举,但是如今,它可能是开箱即用的。
A SO answer about it has been already provided here as toskv pointed out. 正如toskv所指出的, 这里已经提供了一个关于它的SO答案。
As example: 例如:
enum BeerTypes {
lager = "Lager",
ipa = "IPA"
}; };
First, you need to create a base Enum<T>
class. 首先,您需要创建一个基本的
Enum<T>
类。
export class Enum<T> {
public constructor(public readonly value: T) {}
public toString() {
return this.value.toString();
}
}
Create your class that extends Enum<T>
; 创建扩展
Enum<T>
;
export class CompanyMemberTypeEnum extends Enum<string> {
public static readonly DIRECTORS = new Enum('DIRECTORS');
public static readonly SHAREHOLDERS= new Enum('SHAREHOLDERS');
public static readonly DIRECTORS_AND_SHAREHOLDERS = new Enum('DIRECTORS_AND_SHAREHOLDERS');
}
now, you can use your enums like; 现在,您可以像使用枚举一样;
console.log(CompanyMemberTypeEnum.DIRECTORS); // Enum { value: 'DIRECTORS' }
console.log(CompanyMemberTypeEnum.DIRECTORS.value); // DIRECTORS
console.log(CompanyMemberTypeEnum.DIRECTORS.toString()); // DIRECTORS
You can define your enum like: 您可以像这样定义枚举:
export enum CompanyMemberTypeEnum {
DIRECTORS = <any>'Directors',
SHAREHOLDERS = <any>'ShareHolders',
DIRECTORS_AND_SHAREHOLDERS = <any>'Directors and shareholders'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.