我是TypeScript新手,我不明白需要做什么来修复生成TS7015错误的行(使用字符串变量引用枚举成员),因为紧跟其后的行不会出错(使用字符串文字引用枚举成员):

enum State {
    Happy = 0,
    Sad = 1,
    Drunk = 2
}

function Emote(enumKey:string) {
    console.log(State[enumKey]); // error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
    console.log(State["Happy"]); // no error
}

如果检测到错误,则在项目的tsconfig.json中设置"noImplicitAny": true

"noImplictAny": false设置在项目的tsconfig.json中,未检测到任何错误

我用"ntypescript": "^1.201603060104.1"来编译

我现在用"tsc": "1.8.10"美元来编译

C:>npm install -g typescript

`-- typescript@1.8.10

验证安装:

C:\>tsc --version

Version 1.8.10

这是我的tsconfig.json份文件:

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "ES5",
    "module": "System",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "noImplicitAny": true,
    "sourceMap": true,
    "mapRoot": "map/",
    "diagnostics": true
  },
  "exclude": [
    "node_modules",
    "typings"
  ]
}

以下是编译器输出:

C:\>tsc

test.ts(8,17): error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.

推荐答案

如果您使用的是TypeScript 2.1+,可以将enumKey的类型更改为keyof typeof State,如下所示:

function Emote(enumKey: keyof typeof State) {...}

或者,如果函数的输入要求为string,则:

var state : State = State[enumKey as keyof typeof State];

说明:

因为enumKey是一个任意的string,TypeScript不知道enumKey是否是State的成员的名称,所以它会生成一个错误.TypeScript 2.1引入了keyof运算符,它返回类型的已知公共属性名的并集.使用keyof允许我们断言属性确实在目标对象中.

然而,在创建枚举时,TypeScript实际上会生成type(通常是number的子类型)和value(可以在表达式中引用的枚举对象).当你写keyof State时,你实际上会得到一个number的字面属性名的并集.要获取枚举对象的属性名,可以使用keyof typeof State.

资料来源:

https://github.com/Microsoft/TypeScript/issues/13775#issuecomment-276381229

Typescript相关问答推荐

React Hook中基于动态收件箱定义和断言回报类型

TypScript如何在 struct 上定义基元类型?

处理API响应中的日期对象

如何在方法中定义TypeScript返回类型,以根据参数化类型推断变量的存在?

在Typescribe中,extends工作,但当指定派生给super时出错""

输入元素是类型变体的对象数组的正确方法是什么?'

我想创建一个只需要一个未定义属性的打字脚本类型

如何在Reaction路由v6.4加载器和操作中获得Auth0访问令牌?

通过字符串索引访问对象';S的值时出现文字脚本错误

有没有可能产生输出T,它在视觉上省略了T中的一些键?

如果数组使用Reaction-Hook-Form更改,则重新呈现表单

垫表页脚角v15

从对象类型描述生成类型

Typescript 中相同类型的不同结果

打印脚本中正则函数和函数表达式的不同类型缩小行为

编剧- Select 动态下拉选项

在REACT查询中获取未定义的isLoading态

是否可以定义引用另一行中的类型参数的类型?

如何在Type脚本中创建一个只接受两个对象之间具有相同值类型的键的接口?

React-Router V6 中的递归好友路由