Welcome aboard!
When working with TypeScript, I always remind myself that it allows me to do everything I can do with JavaScript, just with added types. This knowledge helps me stay calm when dealing with TypeScript.
The error message is indicating that you cannot use a string
as an index. The reason for this is that in the code snippet this[method]
, method is being used as the index and it is a string. However, in JavaScript, you can access object properties by their names, which means indexing with a string would work (hence no errors in pure JS).
In order to resolve this issue, you need to provide more information to TypeScript to prevent these complaints. One approach could be assigning an any
type to method
, signaling to TypeScript that at runtime, the type will be something usable:
func handleListeningDevice(name: NewNameOption) {
const method:any = !!name ? 'type1Func' : 'type2Func';
this[method]({
name: name ?? 'none',
});
}
You could also consider doing a type casting while using method
:
this[(method as any)]
Alternatively, a type cast for this
can indicate that a string can serve as an index:
(this as {[key:string]:any})[method]
Choose the option that works best for your scenario!