如何在 TypeScript 中创建类似 enum 的类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12687793/
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
How to create enum like type in TypeScript?
提问by eNepper
I'm working on a definitions file for the Google maps API for TypeScript.
我正在为 TypeScript 的 Google 地图 API 编写定义文件。
And I need to define an enum like type eg. google.maps.Animation
which contains two properties: BOUNCE
and DROP
.
我需要定义一个枚举类型,例如。google.maps.Animation
它包含两个属性:BOUNCE
和DROP
。
How should this be done in TypeScript?
这应该如何在 TypeScript 中完成?
回答by Steve Lucco
TypeScript 0.9+ has a specification for enums:
TypeScript 0.9+ 有一个枚举规范:
enum AnimationType {
BOUNCE,
DROP,
}
The final comma is optional.
最后一个逗号是可选的。
回答by Fenton
As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:
从 TypeScript 0.9(目前是 alpha 版本)开始,您可以像这样使用枚举定义:
enum TShirtSize {
? Small,
? Medium,
? Large
}
var mySize = TShirtSize.Large;
By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.
默认情况下,这些枚举将分别指定为 0、1 和 2。如果要显式设置这些数字,可以将其作为枚举声明的一部分进行。
Listing 6.2 Enumerations with explicit members
清单 6.2 具有显式成员的枚举
enum TShirtSize {
? Small = 3,
? Medium = 5,
? Large = 8
}
var mySize = TShirtSize.Large;
Both of these examples lifted directly out of TypeScript for JavaScript Programmers.
这两个例子都是直接从TypeScript for JavaScript Programmers 中提取出来的。
Note that this is different to the 0.8 specification.The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:
请注意,这与 0.8 规范不同。0.8 规范看起来像这样 - 但它被标记为实验性的并且可能会更改,因此您必须更新所有旧代码:
Disclaimer- this 0.8 example would be broken in newer versions of the TypeScript compiler.
免责声明- 这个 0.8 示例在较新版本的 TypeScript 编译器中会被破坏。
enum TShirtSize {
Small: 3,
Medium: 5,
Large: 8
}
var mySize = TShirtSize.Large;
回答by Jeroen
This is now part of the language. See TypeScriptLang.org > Basic Types > enumfor the documentation on this. An excerpt from the documentation on how to use these enums:
这现在是语言的一部分。有关这方面的文档,请参阅TypeScriptLang.org > Basic Types > enum。关于如何使用这些枚举的文档摘录:
enum Color {Red, Green, Blue};
var c: Color = Color.Green;
Or with manual backing numbers:
或者使用手动支持号码:
enum Color {Red = 1, Green = 2, Blue = 4};
var c: Color = Color.Green;
You can also go back to the enum name by using for example Color[2]
.
您还可以使用 example 返回到枚举名称Color[2]
。
Here's an example of how this all goes together:
下面是这一切如何结合的一个例子:
module myModule {
export enum Color {Red, Green, Blue};
export class MyClass {
myColor: Color;
constructor() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
}
}
var foo = new myModule.MyClass();
This will log:
这将记录:
undefined 2 Blue
undefined 2 Blue
Because, at the time of writing this, the Typescript Playground will generate this code:
因为,在撰写本文时,Typescript Playground 将生成以下代码:
var myModule;
(function (myModule) {
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(myModule.Color || (myModule.Color = {}));
var Color = myModule.Color;
;
var MyClass = (function () {
function MyClass() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
return MyClass;
})();
myModule.MyClass = MyClass;
})(myModule || (myModule = {}));
var foo = new myModule.MyClass();
回答by done_merson
Just another note that you can a id/string enum with the following:
请注意,您可以使用以下内容进行 id/string 枚举:
class EnumyObjects{
public static BOUNCE={str:"Bounce",id:1};
public static DROP={str:"Drop",id:2};
public static FALL={str:"Fall",id:3};
}
回答by Arthur
Update:
更新:
As noted by @iX3, Typescript 2.4has support for enum strings.
正如@iX3 所指出的,Typescript 2.4支持枚举字符串。
See:Create an enum with string values in Typescript
Original answer:
原答案:
For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;
对于 String 成员值,TypeScript 只允许数字作为枚举成员值。但是您可以实施一些解决方案/技巧;
Solution 1:
解决方案1:
copied from: 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/
There is a simple solution: Just cast the string literal to any before assigning:
有一个简单的解决方案:只需在分配之前将字符串文字转换为 any 即可:
export enum Language {
English = <any>"English",
German = <any>"German",
French = <any>"French",
Italian = <any>"Italian"
}
solution 2:
解决方案2:
copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html
复制自:https: //basarat.gitbooks.io/typescript/content/docs/types/literal-types.html
You can use a string literal as a type. For example:
您可以使用字符串文字作为类型。例如:
let foo: 'Hello';
Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:
这里我们创建了一个名为 foo 的变量,它只允许将文字值“Hello”分配给它。这在下面演示:
let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"
They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:
它们本身不是很有用,但可以组合在类型联合中以创建强大(且有用)的抽象,例如:
type CardinalDirection =
"North"
| "East"
| "South"
| "West";
function move(distance: number, direction: CardinalDirection) {
// ...
}
move(1,"North"); // Okay
move(1,"Nurth"); // Error!
回答by Willem van der Veen
Enums in typescript:
打字稿中的枚举:
Enums are put into the typescript language to define a set of named constants. Using enums can make our life easier. The reason for this is that these constants are often easier to read than the value which the enum represents.
枚举被放入打字稿语言以定义一组命名常量。使用枚举可以让我们的生活更轻松。这样做的原因是这些常量通常比枚举表示的值更容易阅读。
Creating a enum:
创建枚举:
enum Direction {
Up = 1,
Down,
Left,
Right,
}
This example from the typescript docs explains very nicely how enums work. Notice that our first enum value (Up) is initialized with 1. All the following members of the number enum are then auto incrementedfrom this value (i.e. Down = 2, Left = 3, Right = 4). If we didn't initialize the first value with 1 the enum would start at 0 and then auto increment (i.e. Down = 1, Left = 2, Right = 3).
这个来自打字稿文档的例子很好地解释了枚举是如何工作的。请注意,我们的第一个枚举值 (Up) 初始化为 1。然后数字枚举的所有以下成员都从该值自动递增(即 Down = 2, Left = 3, Right = 4)。如果我们没有用 1 初始化第一个值,枚举将从 0 开始,然后自动递增(即 Down = 1, Left = 2, Right = 3)。
Using an enum:
使用枚举:
We can access the values of the enum in the following manner:
我们可以通过以下方式访问枚举的值:
Direction.Up; // first the enum name, then the dot operator followed by the enum value
Direction.Down;
Notice that this way we are much more descriptivein the way we write our code. Enums basically prevent us from using magic numbers(numbers which represent some entity because the programmer has given a meaning to them in a certain context). Magic numbers are bad because of the following reasons:
请注意,通过这种方式,我们在编写代码的方式上更具描述性。枚举基本上阻止我们使用幻数(代表某个实体的数字,因为程序员在特定上下文中赋予它们含义)。幻数不好的原因如下:
- We need to think harder, we first need to translate the number to an entity before we can reason about our code.
- If we review our code after a long while, or other programmers review our code, they don't necessarily know what is meant with these numbers.
- 我们需要更努力地思考,我们首先需要将数字转换为实体,然后才能对我们的代码进行推理。
- 如果我们在一段时间后查看我们的代码,或者其他程序员查看我们的代码,他们不一定知道这些数字的含义。