Search code examples
typescriptenumsenumeration

Typescript String Enums access


first of all I think I am missing something about Typescript and Enums although I have done all my studies.

So here we go:

I have lets say the following Enum:

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',
}

And at a Class of mine I use it like:

export class Lap  {

  public type: LapTypes;

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

}

When I create a new lap as so:

const lap = new Lap(LapTypes.AutoLap);

All is fine.

Then again if I do this:

const lapType = 'AutoLap';

this new Lap(LapTypes[lapType]) works just fine

However, since I want a dynamic Laptype I am trying to do the following:

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

but when I try to create a new Lap

new Lap(LapTypes[lapType])

I get:

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

I am sure I am missing something fundamendal here and need to restudy my typescipt.

I would like some help on what I am doing wrong and where to look to broaden my knowledge.


Solution

  • Since enum member names are specific strings and not just random strings, string isn't a proper type for enum key.

    If someJSON.Type is any, it can be:

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

    If someJSON.Type has been already typed as string, it can be:

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

    Considering that someJSON is untyped or loosely typed, it should be properly typed as early as possible. keyof typeof LapTypes type should preferably be specified for Type property at someJSON variable definition.