0

The code in my service.ts file is :-

import {injectable} from '@angular/core';
export class ConstantService{
constructor(){}
  public enumTemp = {
 one:'this is one',
 two:'this is two',
 three:'this is three'
}
public GetenumTempMapping(colname: string){
 let keys = Object.keys(this.enumTemp);
 let key=keys.find((i:any) => {
 return i == colname;
}
return this.enumTemp[key];
}
}

I want to pass a string "one" into the function GetenumTempMapping and get the value 'this is one' but for this function is throwing the error in the return statement saying that element implicitly has 'any' type because expression of type string can't be used to index. What am i doing wrong?

Edit:

adding :any to the declaration of enumTemp solved the issue( public enumTemp:any = {one:'one is one'} ). But I think the better way is to add a interface please refer this: For interface implementation provided by @ruth in the comments

phatballz
  • 3
  • 2
  • You say `enum` but seem to be using a plain JS object instead. As such, you can just return the value by referring to the property name: `return this.enumTemp[colname]`. You're getting the error because you're trying to access an object property that doesn't exist. – ruth Feb 17 '22 at 11:46
  • That is the way I initially tried, but was facing the same error, it was throwing the error "No index signature with a parameter of type string was found". – phatballz Feb 17 '22 at 12:47
  • I cannot reproduce your error: https://stackblitz.com/edit/angular-ivy-stepz8?file=src/app/app.component.ts. If however you still get the error, try one of the solutions here: https://stackoverflow.com/q/56568423/6513921 – ruth Feb 17 '22 at 14:23
  • 1
    Thank you @ruth for the link, it helped me resolve the issue. I think we are using strict mode in our project, that is why it is throwing error for me. – phatballz Feb 18 '22 at 13:36

1 Answers1

-1
this.GetenumTempMapping("one");

public GetenumTempMapping(key){
   const val= this.enumTemp[key];
   return val;
    }
  • Please add an explanation to your answers so that they are easier to understand and people can learn from them. – Tim Feb 17 '22 at 10:22
  • I have to give a type to key in declaration "public GetenumTempMapping(key)", I tried using both any and string "public GetenumTempMapping(key: any)/public GetenumTempMapping(key: string)" both of which throw the same error. – phatballz Feb 17 '22 at 10:25
  • Please add this information as an edit to your answer, not as a comment. Comments aren't really meant to be kept forever, answers are. – Luca Kiebel Mar 03 '22 at 12:14