typescript 创建一个带有字符串值的枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15490560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create an enum with string values
提问by FacePalm
Following code can be used to create an enum
in TypeScript:
以下代码可用于enum
在 TypeScript 中创建一个:
enum e {
hello = 1,
world = 2
};
And the values can be accessed by:
并且可以通过以下方式访问这些值:
e.hello;
e.world;
How do I create an enum
with string values?
如何enum
使用字符串值创建一个?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
回答by basarat
TypeScript 2.4
打字稿 2.4
Now has string enums so your code just works:
现在有字符串枚举,所以你的代码可以正常工作:
enum E {
hello = "hello",
world = "world"
};
TypeScript 1.8
打字稿 1.8
Since TypeScript 1.8 you can use string literal types to provide a reliable and safe experience for named string values (which is partially what enums are used for).
从 TypeScript 1.8 开始,您可以使用字符串文字类型为命名字符串值提供可靠且安全的体验(这部分是枚举的用途)。
type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay
foo = "asdf"; // Error!
More : https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types
更多:https: //www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types
Legacy Support
传统支持
Enums in TypeScript are number based.
TypeScript 中的枚举是基于数字的。
You can use a class with static members though:
您可以使用带有静态成员的类:
class E
{
static hello = "hello";
static world = "world";
}
You could go plain as well:
你也可以简单地说:
var E = {
hello: "hello",
world: "world"
}
Update:Based on the requirement to be able to do something like var test:E = E.hello;
the following satisfies this:
更新:基于能够执行var test:E = E.hello;
以下操作的要求满足此要求:
class E
{
// boilerplate
constructor(public value:string){
}
toString(){
return this.value;
}
// values
static hello = new E("hello");
static world = new E("world");
}
// Sample usage:
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;
console.log("First value is: "+ first);
console.log(first===third);
回答by psulek
In latest version (1.0RC) of TypeScript, you can use enums like this:
在 TypeScript 的最新版本 (1.0RC) 中,您可以使用这样的枚举:
enum States {
New,
Active,
Disabled
}
// this will show message '0' which is number representation of enum member
alert(States.Active);
// this will show message 'Disabled' as string representation of enum member
alert(States[States.Disabled]);
Update 1
更新 1
To get number value of enum member from string value, you can use this:
要从字符串值中获取枚举成员的数字值,您可以使用:
var str = "Active";
// this will show message '1'
alert(States[str]);
Update 2
更新 2
In latest TypeScript 2.4, there was introduced string enums, like this:
在最新的 TypeScript 2.4 中,引入了字符串枚举,如下所示:
enum ActionType {
AddUser = "ADD_USER",
DeleteUser = "DELETE_USER",
RenameUser = "RENAME_USER",
// Aliases
RemoveUser = DeleteUser,
}
For more info about TypeScript 2.4, read blog on MSDN.
有关 TypeScript 2.4 的更多信息,请阅读MSDN 上的博客。
回答by David Sherret
TypeScript 2.4+
打字稿 2.4+
You can now assign string values directly to enum members:
您现在可以将字符串值直接分配给枚举成员:
enum Season {
Winter = "winter",
Spring = "spring",
Summer = "summer",
Fall = "fall"
}
See #15486for more information.
有关更多信息,请参阅#15486。
TypeScript 1.8+
打字稿 1.8+
In TypeScript 1.8+, you can create a string literal type to define the type and an object with the same name for the list of values. It mimics a string enum's expected behaviour.
在 TypeScript 1.8+ 中,您可以创建一个字符串字面量类型来定义值列表的类型和同名对象。它模仿字符串枚举的预期行为。
Here's an example:
下面是一个例子:
type MyStringEnum = "member1" | "member2";
const MyStringEnum = {
Member1: "member1" as MyStringEnum,
Member2: "member2" as MyStringEnum
};
Which will work like a string enum:
它将像字符串枚举一样工作:
// implicit typing example
let myVariable = MyStringEnum.Member1; // ok
myVariable = "member2"; // ok
myVariable = "some other value"; // error, desired
// explict typing example
let myExplicitlyTypedVariable: MyStringEnum;
myExplicitlyTypedVariable = MyStringEnum.Member1; // ok
myExplicitlyTypedVariable = "member2"; // ok
myExplicitlyTypedVariable = "some other value"; // error, desired
Make sure to type all the strings in the object! If you don't then in the first example above the variable would not be implicitly typed to MyStringEnum
.
确保键入对象中的所有字符串!如果你不这样做,那么在上面的第一个例子中,变量不会被隐式输入到MyStringEnum
.
回答by MINATO Azuma
In TypeScript 0.9.0.1, although it occurs a compiler error, the compiler can still compile the ts file into js file. The code works as we expected and Visual Studio 2012 can support for automatic code completion.
在 TypeScript 0.9.0.1 中,虽然出现编译错误,但编译器仍然可以将 ts 文件编译为 js 文件。代码按我们的预期工作,Visual Studio 2012 可以支持自动代码完成。
Update :
更新 :
In syntax, TypeScript doesn't allow us to create an enum with string values, but we can hack the compiler :p
在语法上,TypeScript 不允许我们使用字符串值创建枚举,但我们可以破解编译器:p
enum Link
{
LEARN = <any>'/Tutorial',
PLAY = <any>'/Playground',
GET_IT = <any>'/#Download',
RUN_IT = <any>'/Samples',
JOIN_IN = <any>'/#Community'
}
alert('Link.LEARN: ' + Link.LEARN);
alert('Link.PLAY: ' + Link.PLAY);
alert('Link.GET_IT: ' + Link.GET_IT);
alert('Link[\'/Samples\']: Link.' + Link['/Samples']);
alert('Link[\'/#Community\'] Link.' + Link['/#Community']);
回答by Michael Bromley
TypeScript 2.1 +
打字稿 2.1 +
Lookup types, introduced in TypeScript 2.1 allow another pattern for simulating string enums:
在 TypeScript 2.1 中引入的Lookup types允许使用另一种模式来模拟字符串枚举:
// String enums in TypeScript 2.1
const EntityType = {
Foo: 'Foo' as 'Foo',
Bar: 'Bar' as 'Bar'
};
function doIt(entity: keyof typeof EntityType) {
// ...
}
EntityType.Foo // 'Foo'
doIt(EntityType.Foo); //
doIt(EntityType.Bar); //
doIt('Foo'); //
doIt('Bad'); //
TypeScript 2.4 +
打字稿 2.4 +
With version 2.4, TypeScript introduced native support for string enums, so the solution above is not needed. From the TS docs:
在 2.4 版中,TypeScript 引入了对字符串枚举的本机支持,因此不需要上述解决方案。来自 TS 文档:
enum Colors {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
回答by Mient-jan Stelling
Why not just use the native way of accessing the strings of a enum.
为什么不直接使用访问枚举字符串的本机方式。
enum e {
WHY,
NOT,
USE,
NATIVE
}
e[e.WHY] // this returns string 'WHY'
回答by Richard
You can use string enums in the latest TypeScript:
您可以在最新的 TypeScript 中使用字符串枚举:
enum e
{
hello = <any>"hello",
world = <any>"world"
};
Source: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
来源:https: //blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
UPDATE - 2016
更新 - 2016
A slightly more robust way of making a set of strings that I use for React these days is like this:
制作一组我用于 React 的字符串的稍微更健壮的方法是这样的:
export class Messages
{
static CouldNotValidateRequest: string = 'There was an error validating the request';
static PasswordMustNotBeBlank: string = 'Password must not be blank';
}
import {Messages as msg} from '../core/messages';
console.log(msg.PasswordMustNotBeBlank);
回答by Westy92
Here's a fairly clean solution that allows inheritance, using TypeScript 2.0. I didn't try this on an earlier version.
这是一个相当干净的解决方案,允许继承,使用 TypeScript 2.0。我没有在早期版本上尝试过这个。
Bonus:the value can be anytype!
奖励:值可以是任何类型!
export class Enum<T> {
public constructor(public readonly value: T) {}
public toString() {
return this.value.toString();
}
}
export class PrimaryColor extends Enum<string> {
public static readonly Red = new Enum('#FF0000');
public static readonly Green = new Enum('#00FF00');
public static readonly Blue = new Enum('#0000FF');
}
export class Color extends PrimaryColor {
public static readonly White = new Enum('#FFFFFF');
public static readonly Black = new Enum('#000000');
}
// Usage:
console.log(PrimaryColor.Red);
// Output: Enum { value: '#FF0000' }
console.log(Color.Red); // inherited!
// Output: Enum { value: '#FF0000' }
console.log(Color.Red.value); // we have to call .value to get the value.
// Output: #FF0000
console.log(Color.Red.toString()); // toString() works too.
// Output: #FF0000
class Thing {
color: Color;
}
let thing: Thing = {
color: Color.Red,
};
switch (thing.color) {
case Color.Red: // ...
case Color.White: // ...
}
回答by nishantkyal
A hacky way to this is: -
一个hacky的方法是: -
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]];
}
How to use
如何使用
Utils.getEnumString(Status, Status.COMPLETED); // = "COMPLETED"
回答by James Wilkins
This works for me:
这对我有用:
class MyClass {
static MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
or
或者
module MyModule {
export var MyEnum: { Value1; Value2; Value3; }
= {
Value1: "Value1",
Value2: "Value2",
Value3: "Value3"
};
}
8)
8)
Update: Shortly after posting this I discovered another way, but forgot to post an update (however, someone already did mentioned it above):
更新:发布后不久我发现了另一种方式,但忘记发布更新(但是,上面已经有人提到过):
enum MyEnum {
value1 = <any>"value1 ",
value2 = <any>"value2 ",
value3 = <any>"value3 "
}