请教一下 typescript 下 enum 的 name 和 value 的问题?

2020-10-29 09:22:24 +08:00
 yazoox
enum Month {  
    Jan='January',  
    Feb = 'February',  
    Mar='March'  
}

console.log(Month.Feb);
  
for(var n in Month) {  
    console.log(n);
    console.log(Month[n]);
}  

输出如下:

[LOG]: "February" 
[LOG]: "Jan" 
[LOG]: "January" 
[LOG]: "Feb" 
[LOG]: "February" 
[LOG]: "Mar" 
[LOG]: "March" 

但是编译器总是“提示”/“报错”:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Month'. No index signature with a parameter of type 'string' was found on type 'typeof Month'.

string 不能用于 enum 访问的 index 么?

但是结果,似乎又能够正常工作。不是很理解。

又比如:

const a : Month = Month["Jan"];
console.log(a);
console.log(typeof a);
[LOG]: "January" 
[LOG]: "string" 

我已经指定 a 的 type 是 Month,编译器没有报错,但是打印出来,typeof a 是 string

翻了半天 typescript 的文档,貌似也没有解释得很清楚。

1906 次点击
所在节点    TypeScript
7 条回复
noe132
2020-10-29 09:40:12 +08:00
enum 不应该当作 object 来用。
const enum 实际上根本不存在 runtine object 。
而且 number enum 有 reverse mapping 。
Perry
2020-10-29 09:44:27 +08:00
TypeScript 最后会 transpile 成 JavaScript,这些 enum 最后还是会变成你定义的 string
xiaojie668329
2020-10-29 09:54:01 +08:00
Month 是个类型,你把它当值来用不大合适吧。虽然 enum 的特性最终是可以遍历的。
yazoox
2020-10-29 10:12:44 +08:00
@noe132 研究了一下,确实。直接使用 number enum 更好。反正他也会添加 string 的(通过 reverse maaping )
gouflv
2020-10-29 10:49:29 +08:00
enum 我一般会再配合一个 {[enumKey]:name }的对象做取值
yazoox
2020-10-29 14:44:33 +08:00
@gouflv 不好意思,能多讲一些么?没有看明白。谢谢!
ifsct
2020-10-29 14:55:12 +08:00
后半部分,你是不是弄混了 ts 的 typeof 和 js 的 typeof😢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/719654

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX