1

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

2 Answers 2

1

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(""));
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.