以下代码可用于在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
};
当前回答
我认为你应该试试这个,在这种情况下,变量的值不会改变,它的工作方式很像枚举,使用类也可以,唯一的缺点是你可以错误地改变静态变量的值这是我们不希望在枚举中发生的。
namespace portal {
export namespace storageNames {
export const appRegistration = 'appRegistration';
export const accessToken = 'access_token';
}
}
其他回答
最近在使用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)
//to access the enum with its string value you can convert it to object
//then you can convert enum to object with proberty
//for Example :
enum days { "one" =3, "tow", "Three" }
let _days: any = days;
if (_days.one == days.one)
{
alert(_days.one + ' | ' + _days[4]);
}
我正在寻找一种方法来实现typescript枚举中的描述(v2.5),这种模式适合我:
export enum PriceTypes {
Undefined = 0,
UndefinedDescription = 'Undefined' as any,
UserEntered = 1,
UserEnteredDescription = 'User Entered' as any,
GeneratedFromTrade = 2,
GeneratedFromTradeDescription = 'Generated From Trade' as any,
GeneratedFromFreeze = 3,
GeneratedFromFreezeDescription = 'Generated Rom Freeze' as any
}
...
GetDescription(e: any, id: number): string {
return e[e[id].toString() + "Description"];
}
getPriceTypeDescription(price: IPricePoint): string {
return this.GetDescription(PriceTypes, price.priceType);
}
小js-hack但工作:e[字符串(e.hello)]
使用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'