Home > Mobile >  TypeScript Angular: No index signature with a parameter of type 'string' was found
TypeScript Angular: No index signature with a parameter of type 'string' was found

Time:09-06

I have a component that takes information from a service, and I would like to use a forEach statement to initialize component's properties. This does not work:

const variables = ['records' ,'observableComplete' ]
variables.forEach(variable => {
  this.user2RoleService[variable].subscribe( result => { this[variable] = result})
});

But this does work (but I should do it one by one)

const variable = 'observableComplete'
this.user2RoleService[variable].subscribe( result => { this[variable] = result})

Any thoughts how to solve it?

CodePudding user response:

you should use this() instead of [].

const variables = ['records' ,'observableComplete' ]
variables.forEach(variable => {
  this.user2RoleService(variable).subscribe( result => { this[variable] =result})
});

CodePudding user response:

I'm assuming your user2RoleService is an instance of a class User2RoleService. Therefore, this type declaration should do:

const variables: (keyof User2RoleService)[] = ['records', 'observableComplete'];

CodePudding user response:

I'm afraid that in strict mode you need an "ugly hack"

const variables = ['records', 'observableComplete'];

const self=this as any  //<--this is the uggly hack

variables.forEach((variable: string) => {
  self.user2RoleService[variable].subscribe((result: any) => {
    self[variable]=result;
    console.log(this.records,this.observableComplete) //<--only for check
  });
});

CodePudding user response:

the way you are doing the assignment typescript infers it as string[], however you can improve it with the help of as const. simply do

const variables = ['records' ,'observableComplete' ] as const;

and then the type of variables will be the same tuple provided

  • Related