以下代码可用于在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
};
当前回答
//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@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'
更新:TypeScript 3.4
你可以简单地使用const:
const AwesomeType = {
Foo: "foo",
Bar: "bar"
} as const;
打字稿2.1
这也可以用这种方式完成。希望它能帮助到一些人。
const AwesomeType = {
Foo: "foo" as "foo",
Bar: "bar" as "bar"
};
type AwesomeType = (typeof AwesomeType)[keyof typeof AwesomeType];
console.log(AwesomeType.Bar); // returns bar
console.log(AwesomeType.Foo); // returns foo
function doSth(awesometype: AwesomeType) {
console.log(awesometype);
}
doSth("foo") // return foo
doSth("bar") // returns bar
doSth(AwesomeType.Bar) // returns bar
doSth(AwesomeType.Foo) // returns foo
doSth('error') // does not compile
export enum PaymentType {
Cash = 1,
Credit = 2
}
var paymentType = PaymentType[PaymentType.Cash];
我正在寻找一种方法来实现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);
}
为什么不直接使用本地方式访问枚举的字符串呢?
enum e {
WHY,
NOT,
USE,
NATIVE
}
e[e.WHY] // this returns string 'WHY'