元素隐式地具有“ any”类型,因为在打字稿中将字符串转换为enum时,索引表达式不是enum的“ number”类型

Vip*_*pin 4 typescript

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

enum Categories {
    textbox = 1,
    password
}

let typedata:string ="textbox";
let enumdata:Categories;
Run Code Online (Sandbox Code Playgroud)

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

enumdata=Categories[typedata]
Run Code Online (Sandbox Code Playgroud)

我遇到错误

元素隐式具有“ any”类型,因为索引表达式不是“ number”类型

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

我的打字稿版本是2.6.2

tsconfig.json

{
  "compilerOptions": {
      "module": "commonjs",
      "target": "es6",
      "lib": [
        "dom",
        "es2015"
      ],
      "noImplicitAny": false,
      "sourceMap": true,
      "rootDir": "src",
      "outDir": "dist",
      "noEmitOnError": true
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢Vipin

Sha*_*ard 5

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

它期望标识符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);
Run Code Online (Sandbox Code Playgroud)

...或者干脆

const typedata: string = "textbox";
enumdata = Categories[typedata as CategoryType];
Run Code Online (Sandbox Code Playgroud)