打字稿0.9后发布: enums are now supported:
enum Select { every, first, last }
原始问题:
这里讨论了打字稿中的枚举,但没有解决方案导致环境设计 . 环境枚举定义意味着枚举仅由编译器处理,而编译的js输出文件仅处理原始数值 . 就像在C 11中一样 .
我得到的最接近的是
declare var Color = { red: 1, blue: 2, green: 3 } // DOES NOT COMPILE
但是编译器不接受这个:“Ambient变量不能有初始化器” .
edit
结合dmck的答案:
declare var Color: { Red: number; Green: number; Blue: number; };
这不会输出任何js代码 . 换句话说,它是环境 . 然而,这也使它无用:
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);
}
将产生运行时错误,因为未在js中定义Color . ts声明只是声称js中有一些Color对象,而事实上,没有定义,没有 . 我们可以添加Ti解决这个问题
var Color = {
Red: 1,
Green: 2,
Blue: 3
};
但是现在enum实现不是"ambient",因为typescript编译器执行C编译器所做的事情,将所有出现的枚举值减少为普通数字 . The current ambient declarations allow type checking but not such replacement.
3 回答
TypeScript 0.9允许这样:
添加答案,因为有从TypeScript 1.4开始的新功能;
使用
const enum
给出预期的结果 .这是一个正常的枚举:
这是一个const enum:
这篇博客文章解释了更多细节:https://tusksoft.com/blog/posts/11/const-enums-in-typescript-1-4-and-how-they-differ-from-standard-enums
你可以这样做:
请记住,按设计 ambient declarations have no effect on the output of your code . 所以某处你需要实际声明Color和每个枚举成员的值 .