Is there a way to create enums in typescript that are ambient?

after the release of typescript 0.9: are listed:

enum Select { every, first, last } 

original question:

Enumerations in typescript were discussed here, but no solution led to the creation of an ambient design. The definition of enum enum will mean that the enumeration is processed only by the compiler, and the compiled output js files only process unprocessed numeric values. Like in C ++ 11.

The closest I get

 declare var Color = { red: 1, blue: 2, green: 3 } // DOES NOT COMPILE 

but the compiler does not accept this: "An environment variable cannot have an initializer."

change
including dmck answer:

 declare var Color: { Red: number; Green: number; Blue: number; }; 

This does not output js code. In other words, it's ambient. However, this makes it useless:

 declare var Color: { Red: number; Green: number; Blue: number; }; function test() { var x = Color.Blue; // null ref exception, no Color object console.log(x == Color.Red); } 

will result in a runtime error since the color is not defined in js. The ts declaration simply states that there is some Color object in js, but in fact there is no definition. Ti fix it we can add

 var Color = { Red: 1, Green: 2, Blue: 3 }; 

but now the enum implementation is not "ambient" in the sense that the typescript compiler does what the C ++ compiler does, reducing the enumeration values ​​to prime numbers in all cases. Current ambient ads let you check the type, but not such a replacement.

+4
source share
3 answers

TypeScript 0.9 allows you to:

 declare module A { export enum E { X, Y, Z } } 
+4
source

You can do something like this:

 declare var Color: { Red: number; Green: number; Blue: number; }; 

Remember that ambient design does not affect the output of your code . So somewhere, you will need to declare the color and values ​​of each member of the enumeration.

+1
source

Adding an answer, as new functions begin for this, starting with TypeScript 1.4;

using const enum , give the expected result.

This is with a normal listing:

 //TypeScript: enum StandardEnum {FirstItem, SecondItem, ThirdItem}; //Compiled javascript: var StandardEnum; (function (StandardEnum) { StandardEnum[StandardEnum["FirstItem"] = 0] = "FirstItem"; StandardEnum[StandardEnum["SecondItem"] = 1] = "SecondItem"; StandardEnum[StandardEnum["ThirdItem"] = 2] = "ThirdItem"; })(StandardEnum || (StandardEnum = {})); 

This is with a constant listing:

 //TypeScript: const enum ConstantEnum { FirstItem, SecondItem, ThirdItem }; //Compiled javascript: ; 

This blog post explains this in more detail: https://tusksoft.com/blog/posts/11/const-enums-in-typescript-1-4-and-how-they-differ-from-standard-enums

+1
source

All Articles