打字稿字符串枚举访问

Typescript String Enums access

首先,尽管我已经完成了所有的学习,但我认为我遗漏了一些关于 Typescript 和 Enums 的东西。

我们开始吧:

我有以下枚举:

export enum LapTypes {
  'Start' = 'Start',
  'Stop' = 'Start',
  'Manual' = 'Manual',
  'manual' = 'Manual',
  'Autolap' = 'Auto lap',
  'AutoLap' = 'Auto lap',
  'autolap' = 'Auto lap',
  'Distance' = 'Distance',
  'distance' = 'Distance',
  'Location' = 'Location',
  'location' = 'Location',
  'Time' = 'Time',
  'time' = 'Time',
  'HeartRate' = 'Heart Rate',
  'position_start' = 'Position start',
  'position_lap' = 'Position lap',
  'position_waypoint' = 'Position waypoint',
  'position_marked' = 'Position marked',
  'session_end' = 'Session end',
  'fitness_equipment' = 'Fitness equipment',
}

在我的 Class 中,我像这样使用它:

export class Lap  {

  public type: LapTypes;

  constructor(type: LapTypes) {
    this.type = type;
  }

}

当我这样创建一个新圈时:

const lap = new Lap(LapTypes.AutoLap);

一切都很好。

然后如果我这样做:

const lapType = 'AutoLap';

这个new Lap(LapTypes[lapType])工作得很好

但是,因为我想要一个动态的 Laptype,所以我正在尝试执行以下操作:

const lapType: string = someJSON['Type'];

但是当我尝试创建新的 Lap

new Lap(LapTypes[lapType])

我得到:

element implicitly has an 'any' type because index expression is not of type 'number'

我确定我在这里遗漏了一些基本知识,需要重新研究我的打字稿。

我想知道我做错了什么以及在哪里可以扩展我的知识。

只需使用:new Lap(LapTypes[lapType as LapTypes])

由于枚举成员名称是特定字符串而不仅仅是随机字符串,因此 string 不是枚举键的正确类型。

如果someJSON.Typeany,可以是:

const lapType: keyof typeof LapTypes = someJSON['Type'];
new Lap(LapTypes[lapType]);

如果someJSON.Type已经输入为string,它可以是:

const lapType = <keyof typeof LapTypes>someJSON['Type'];
new Lap(LapTypes[lapType]);

考虑到someJSON是无类型或松散类型的,应尽早正确类型化。 keyof typeof LapTypes 类型最好在 someJSON 变量定义中为 Type 属性 指定。