繁体   English   中英

为什么 TypeScript 抱怨枚举上的字符串索引?

[英]Why does TypeScript complain about string index on an enum?

下面的 TypeScript 代码在某些情况下使用带有枚举的字符串索引存在错误,但在其他情况下则不然。 此外,在某些环境中,带有“错误”的代码无论如何都会运行。

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? */

typescriptlang.org 的 Playground中查看此操作。

我不明白为什么在 map function 中,我得到关于使用字符串索引的错误。 但是,直接使用字符串从枚举中获取单个值可以正常工作。

我也不明白为什么 Playground 会报告错误,但它还是会运行。 在我自己的计算机上,如果我尝试运行它,它会在执行任何操作之前失败。

类型string可能有更具体的类型。 类型可以是特定的字符串。

所以当你这样做时:

const roles: string[] = ['AccountAdmin', 'SupportConsultant']
console.log(roles.map(r => LMSRole[r]))

rolesstring类型的数组。 但是LMSRole只有非常具体的字符串可以用作索引,所以你会得到错误。

在哪里:

console.log(LMSRole['SupportConsultant'])

Typescript 知道,因为你直接使用了一个字符串字面量,那个字符串的具体类型是什么,并且知道它是一个好的。

如果您将其更改为:

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)

然后你会得到一个有意义的错误。

您可以强制 typescript 将您的数组视为常量,这样它就可以推断出特定的字符串类型,如下所示:

const roles = ['AccountAdmin', 'SupportConsultant'] as const
console.log(roles.map(r => LMSRole[r])) // no error

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM