[英]Why does TypeScript complain about string index on an enum?
The TypeScript code below has errors about using a string index with an enum in some cases, but not in others.下面的 TypeScript 代码在某些情况下使用带有枚举的字符串索引存在错误,但在其他情况下则不然。 Also, in some environments, the code with "errors" runs anyway.
此外,在某些环境中,带有“错误”的代码无论如何都会运行。
enum LMSRole {
AccountAdmin = 'Account Admin',
SupportConsultant = 'Support Consultant',
StudentEnrollment = 'StudentEnrollment',
TeacherEnrollment = 'TeacherEnrollment'
}
console.log(LMSRole.SupportConsultant) /* "Support Consultant" - OK */
const roles: String[] = ['AccountAdmin', 'SupportConsultant']
console.log(roles.map(r => LMSRole[r]))
/* Error given, yet runs on (http://typescriptlang.org/play)...
* Type 'String' cannot be used as an index type. */
console.log(LMSRole['SupportConsultant']) /* "Support Consultant" - OK */
/* In this example, a type of 'String' is used as an index,
* but there's no error. Why? */
See this in action at typescriptlang.org's Playground .在typescriptlang.org 的 Playground中查看此操作。
What I don't understand is why in the map function, I get the error about using the string index.我不明白为什么在 map function 中,我得到关于使用字符串索引的错误。 However, using a string directly to get a single value from the enum works without error.
但是,直接使用字符串从枚举中获取单个值可以正常工作。
I also don't understand why the Playground reports an error, but it runs anyway.我也不明白为什么 Playground 会报告错误,但它还是会运行。 On my own computer, if I try to run it, it will fail before anything is executed.
在我自己的计算机上,如果我尝试运行它,它会在执行任何操作之前失败。
The type string
may have more specific types.类型
string
可能有更具体的类型。 The type could be specific strings.类型可以是特定的字符串。
So when you do this:所以当你这样做时:
const roles: string[] = ['AccountAdmin', 'SupportConsultant']
console.log(roles.map(r => LMSRole[r]))
roles
is an array of string
types. roles
是string
类型的数组。 But the LMSRole
only has very specific strings that you can use as an index, so you get the error.但是
LMSRole
只有非常具体的字符串可以用作索引,所以你会得到错误。
Where here:在哪里:
console.log(LMSRole['SupportConsultant'])
Typescript knows, because you directly used a string literal, what the specific type of that string is, and knows it's a good one. Typescript 知道,因为你直接使用了一个字符串字面量,那个字符串的具体类型是什么,并且知道它是一个好的。
If you changed that to:如果您将其更改为:
LMSRole['SomethingElse']
//Element implicitly has an 'any' type because expression of type '"SomethingElse"' can't be used to index type 'typeof LMSRole'.
// Property 'SomethingElse' does not exist on type 'typeof LMSRole'.(7053)
Then you get an error that makes sense.然后你会得到一个有意义的错误。
You can force typescript to treat your array as constants, which lets it infer the specific strings types like so:您可以强制 typescript 将您的数组视为常量,这样它就可以推断出特定的字符串类型,如下所示:
const roles = ['AccountAdmin', 'SupportConsultant'] as const
console.log(roles.map(r => LMSRole[r])) // no error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.