以下代码可用于在TypeScript中创建enum:
enum e {
hello = 1,
world = 2
};
这些值可以通过以下方式访问:
e.hello;
e.world;
我如何创建一个字符串值enum ?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
以下代码可用于在TypeScript中创建enum:
enum e {
hello = 1,
world = 2
};
这些值可以通过以下方式访问:
e.hello;
e.world;
我如何创建一个字符串值enum ?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
当前回答
最近在使用TypeScript 1.0.1时遇到了这个问题,并以这种方式解决了:
enum IEvents {
/** A click on a product or product link for one or more products. */
CLICK,
/** A view of product details. */
DETAIL,
/** Adding one or more products to a shopping cart. */
ADD,
/** Remove one or more products from a shopping cart. */
REMOVE,
/** Initiating the checkout process for one or more products. */
CHECKOUT,
/** Sending the option value for a given checkout step. */
CHECKOUT_OPTION,
/** The sale of one or more products. */
PURCHASE,
/** The refund of one or more products. */
REFUND,
/** A click on an internal promotion. */
PROMO_CLICK
}
var Events = [
'click',
'detail',
'add',
'remove',
'checkout',
'checkout_option',
'purchase',
'refund',
'promo_click'
];
function stuff(event: IEvents):boolean {
// event can now be only IEvents constants
Events[event]; // event is actually a number that matches the index of the array
}
// stuff('click') won't work, it needs to be called using stuff(IEvents.CLICK)
其他回答
如果你想要的主要是易于调试(相当类型检查),不需要为枚举指定特殊值,这是我正在做的:
export type Enum = { [index: number]: string } & { [key: string]: number } | Object;
/**
* inplace update
* */
export function enum_only_string<E extends Enum>(e: E) {
Object.keys(e)
.filter(i => Number.isFinite(+i))
.forEach(i => {
const s = e[i];
e[s] = s;
delete e[i];
});
}
enum AuthType {
phone, email, sms, password
}
enum_only_string(AuthType);
如果您希望支持遗留代码/数据存储,则可以保留数字键。
这样,您就可以避免键入两次值。
一个俗套的说法是:-
CallStatus.ts
enum Status
{
PENDING_SCHEDULING,
SCHEDULED,
CANCELLED,
COMPLETED,
IN_PROGRESS,
FAILED,
POSTPONED
}
export = Status
Utils.ts
static getEnumString(enum:any, key:any):string
{
return enum[enum[key]];
}
如何使用
Utils.getEnumString(Status, Status.COMPLETED); // = "COMPLETED"
使用typescript@next中提供的自定义转换器(https://github.com/Microsoft/TypeScript/pull/13940),您可以从字符串字面类型创建字符串值的枚举对象。
请查看我的npm包,ts-transformer-enumerate。
使用示例:
// The signature of `enumerate` here is `function enumerate<T extends string>(): { [K in T]: K };`
import { enumerate } from 'ts-transformer-enumerate';
type Colors = 'green' | 'yellow' | 'red';
const Colors = enumerate<Colors>();
console.log(Colors.green); // 'green'
console.log(Colors.yellow); // 'yellow'
console.log(Colors.red); // 'red'
非常非常简单的Enum string (TypeScript 2.4)
import * from '../mylib'
export enum MESSAGES {
ERROR_CHART_UNKNOWN,
ERROR_2
}
export class Messages {
public static get(id : MESSAGES){
let message = ""
switch (id) {
case MESSAGES.ERROR_CHART_UNKNOWN :
message = "The chart does not exist."
break;
case MESSAGES.ERROR_2 :
message = "example."
break;
}
return message
}
}
function log(messageName:MESSAGES){
console.log(Messages.get(messageName))
}
@basarat的回答很棒。下面是一个你可以使用的简化但有点扩展的例子:
export type TMyEnumType = 'value1'|'value2';
export class MyEnumType {
static VALUE1: TMyEnumType = 'value1';
static VALUE2: TMyEnumType = 'value2';
}
console.log(MyEnumType.VALUE1); // 'value1'
const variable = MyEnumType.VALUE2; // it has the string value 'value2'
switch (variable) {
case MyEnumType.VALUE1:
// code...
case MyEnumType.VALUE2:
// code...
}