Home > Back-end >  Typescript - Accessing value from enum
Typescript - Accessing value from enum

Time:07-13

I was trying to solve a typescript challenge and encountered this issue Element implicitly has an 'any' type because index expression is not of type 'number'. on this line Resistors[val] I'm not sure what I'm doing wrong here. If anyone could direct me here, that'd be really helpful. Thanks in advance!

enum Resistors {
  Black = 0,
  Brown = 1,
  Red = 2,
  Orange = 3,
  Yellow = 4,
  Green = 5,
  Blue = 6,
  Violet = 7,
  Grey = 8,
  White = 9
} 

export function decodedValue(labels : string[]) {
  let valuesArr: string[] = labels.map((value: string) => {
    const val: string = value.charAt(0).toUpperCase()   value.slice(1);
     return Resistors[val];
  });
  return Number(valuesArr.join(''));
}

console.log(decodedValue(['brown', 'black']));

CodePudding user response:

Your issue here is that you're trying to access the enum with an arbitrary string. The value of val has to be one of the Resistor colors.

enum Resistors {
  Black = 0,
  Brown = 1,
  Red = 2,
  Orange = 3,
  Yellow = 4,
  Green = 5,
  Blue = 6,
  Violet = 7,
  Grey = 8,
  White = 9
} 

 function decodedValue(labels : string[]) {
  let valuesArr: string[] = labels.map((value: string) => {
    const val: Resistors = (value.charAt(0).toUpperCase()   value.slice(1)) as unknown as Resistors;
    return Resistors[val];
  });
  return Number(valuesArr.join(''));
}

console.log(decodedValue(['brown', 'black']));

I'm not sure if there is a better way than as unknown as Resistors.

CodePudding user response:

First of all, your Enum should look like this (source):

enum Resistors {
  Black,
  Brown,
  Red,
  Orange,
  Yellow,
  Green,
  Blue,
  Violet,
  Grey,
  White,
}

Second of all, here is the source on how to access an Enum's property.

Then, something like this would work:

export function decodedValue(labels: string[]) {
  let valuesArr: number[] = labels.map((value: string) => {
    const val: string = value.charAt(0).toUpperCase()   value.slice(1);
    return Resistors[val as keyof typeof Resistors];
  });
  return Number(valuesArr.join(""));
}
  • Related