Home > Software engineering >  Element implicitly has an 'any' type because expression of type 'keyof ObjProp'
Element implicitly has an 'any' type because expression of type 'keyof ObjProp'

Time:08-02

class MyStatic {
  static group = {
    name:(value:string):string => {
      console.log(value);
      return value;
    },
    age:(value:string):string => {
      console.log(value);
      return value;
    }
  }
}

interface ObjProp {
  value:string;
  label:string;
}

const values:ObjProp[] = [{value:'nameValue', label:'name'}, {value:'ageValue', label:'age'}];

for(let m of values) {
  console.log(m.label);
  MyStatic.group[m.label as keyof ObjProp](); //error i am getting
}

Playground

CodePudding user response:

It's works for me:

 class MyStatic {
  static group:Record<string, (s:string)=>string> = {
    name:(value:string):string => {
      return value;
    },
    age:(value:string):string => {
      return value;
    }
  }
}

interface ObjProp {
  value:string;
  label:string;
}

const values:ObjProp[] = [{value:'nameValue', label:'name'}, {value:'ageValue', label:'age'}];

for(let m of values) {
  const Value = MyStatic.group[m.label](m.value); 
  console.log(Value)
}

CodePudding user response:

Rather than

MyStatic.group[m.label as keyof ObjProp]();

you probably wanted

MyStatic.group[m.label as keyof typeof MyStatic.group](); 

however, both methods still need an argument, e.g.

MyStatic.group[m.label as keyof typeof MyStatic.group]('foo'); 
  • Related