【发布时间】:2018-10-23 05:40:59
【问题描述】:
首先,尽管我已经完成了所有的研究,但我认为我缺少关于 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]) 工作得很好
但是,由于我想要一个动态的笔记本电脑,我正在尝试执行以下操作:
const lapType: string = someJSON['Type'];
但是当我尝试创建一个新的圈时
new Lap(LapTypes[lapType])
我明白了:
元素隐式具有“任意”类型,因为索引表达式不是“数字”类型
我确定我在这里遗漏了一些基本的东西,需要重新研究我的打字机。
我想要一些关于我做错了什么以及在哪里可以扩展我的知识的帮助。
【问题讨论】:
-
JSON 中的 laptype 是您期望的还是其他值?还有你使用枚举的方式,对我来说,地图似乎更合适。
-
@MarkoTaht 它在 JSON 中是一个刺痛,我在编译类型中得到它。在排序它不会让我编译。我正在使用最新的 TS。我可以将其设为带有索引的地图或 const,但我想使用 Enum as of API first 方法来缩小案例范围。
-
stackoverflow.com/questions/36316326/… 这里有人遇到了同样的问题。你要做的是 LapTypes[
lapType]. -
const lapType = <keyof typeof LapTypes>someJSON['Type']这样的东西有用吗? -
@MarkoTaht 不起作用
标签: typescript enums enumeration