打字稿字符串枚举访问



首先,我认为我错过了一些关于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',
}

在我的一类课上,我像这样使用它:

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'];

但是当我尝试创建一个新的圈数时

new Lap(LapTypes[lapType])

我得到:

元素隐式具有"any"类型,因为索引表达式不是"数字"类型

我确信我在这里错过了一些基本修正的东西,需要重新研究我的类型。

我想得到一些帮助,了解我做错了什么,以及在哪里寻找以拓宽我的知识。

由于枚举成员名称是特定的字符串,而不仅仅是随机字符串,因此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变量定义someJSONType属性指定类型。

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

最新更新