benntyGoodla
benntyGoodla

Reputation: 81

Typescript Vue: using a dynamic string name for a method

My goal is to have a different function fired depending on a variable value. VS Code is giving me an error warning stating that:

'method' implicitly has a type of 'any' because 'type1Func' and 'type1Func' are strings and can't be used as an index. I am using a similar technique on a normal Vue js file successfully but I don't know how to resolve this in this typescript file.

func handleListeningDevice(name: NewNameOption) {
  const method = !!name ? 'type1Func' : 'type2Func';
  
  this[method]({
    name: name ?? 'none',
  });
}

Upvotes: 3

Views: 552

Answers (1)

Roberto Langarica
Roberto Langarica

Reputation: 729

First of all welcome.

One thing that I keep in mind whenever I'm using TypeScript is that you can do the same you do with JS (since it is JS but with types) it helps me keep my calm with TS.

The error message is saying that you can't use string as an index and that is because in the code this[method] method is the index and method is a string, but as you already know you can access object properties by name in other words indexed with a string (so the code will work in pure JS)

In order for it to work you need to give more information to TS so it stops complaining. You could for example give it an any type to method, with that you are telling TS that in runtime the type will be something that could be used

 func handleListeningDevice(name: NewNameOption) {
  const method:any = !!name ? 'type1Func' : 'type2Func';

  this[method]({
   name: name ?? 'none',
  });
}

Or you can also do a type casting while using method:

this[(method as any)]

Or a type cast for this to indicate that a string can be an index:

(this as {[key:string]:any})[method]

Check what suits you best!

Upvotes: 3

Related Questions