跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 请教一下 typescript 下 enum 的 name 和 value 的问题?
未分類
30 10 月 2020

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

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

資深大佬 : yazoox 1

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 的文档,貌似也没有解释得很清楚。

大佬有話說 (7)

  • 資深大佬 : noe132

    enum 不应该当作 object 来用。
    const enum 实际上根本不存在 runtine object 。
    而且 number enum 有 reverse mapping 。

  • 資深大佬 : Perry

    TypeScript 最后会 transpile 成 JavaScript,这些 enum 最后还是会变成你定义的 string

  • 資深大佬 : xiaojie668329

    Month 是个类型,你把它当值来用不大合适吧。虽然 enum 的特性最终是可以遍历的。

  • 主 資深大佬 : yazoox

    @noe132 研究了一下,确实。直接使用 number enum 更好。反正他也会添加 string 的(通过 reverse maaping )

  • 資深大佬 : gouflv

    enum 我一般会再配合一个 {[enumKey]:name }的对象做取值

  • 主 資深大佬 : yazoox

    @gouflv 不好意思,能多讲一些么?没有看明白。谢谢!

  • 資深大佬 : ifsct

    后半部分,你是不是弄混了 ts 的 typeof 和 js 的 typeof

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具