【问题标题】:Element implicitly has an 'any' type because the index expression is not of type 'number' for enum while converting string to enum in typescript元素隐式具有“任何”类型,因为在打字稿中将字符串转换为枚举时,索引表达式不是枚举的“数字”类型
【发布时间】:2018-05-31 06:39:26
【问题描述】:

我有一个如下所示的打字稿。

enum Categories {
    textbox = 1,
    password
}

let typedata:string ="textbox";
let enumdata:Categories;

我想将此文本框字符串转换为枚举。这样我就可以在 enumdata 变量中分配它。当我尝试使用

enumdata=Categories[typedata]

我遇到了一个错误

元素隐式具有“任意”类型,因为索引表达式不是“数字”类型

如果有人遇到此问题,请告诉我。如果您找到了解决方案,请提供示例。

我的打字稿版本是 2.6.2

tsconfig.json

{
  "compilerOptions": {
      "module": "commonjs",
      "target": "es6",
      "lib": [
        "dom",
        "es2015"
      ],
      "noImplicitAny": false,
      "sourceMap": true,
      "rootDir": "src",
      "outDir": "dist",
      "noEmitOnError": true
  }
}

谢谢 维平

【问题讨论】:

    标签: typescript


    【解决方案1】:

    在打字稿中,枚举只能通过数字和确切的属性名称来索引。

    它需要标识符textbox0,类型为"textbox"number,但接收该值作为字符串类型。

    要解决这个问题,您可以声明一个类型,以确保使用正确的属性名称来获取相应的枚举值。例如:

    enum Categories {
        textbox = 1,
        password
    }
    
    declare type CategoryType = keyof typeof Categories;
    
    const getCategory = (key: CategoryType) => Categories[key];
    /* The following will work as well, but does not ensure the correct typecheck when calling the function. 
       However you can keep you 'typedata' field as type of  string. */
    // const getCategory = (key: string) => Categories[key as CategoryType];
    
    let enumdata: Categories;
    const typedata: CategoryType = "textbox";
    
    enumdata = getCategory(typedata);
    

    ...或者干脆

    const typedata: string = "textbox";
    enumdata = Categories[typedata as CategoryType];
    

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2021-04-23
      • 1970-01-01
      • 2018-04-25
      • 2018-02-14
      • 2023-04-01
      • 2018-07-05
      • 2019-10-30
      • 2019-03-04
      相关资源
      最近更新 更多