Reputation: 13
Is it possible to map a string to a function using TS. For example :
this.keyBinding = new Map<string, Function>();
this.keyBinding
.set('Backspace', this.handleBackspace)
.set('Delete', this.handleDelete)
I tried to execute it using:
this.keyBinding.get('Backspace');
but nothing happens.
Upvotes: 1
Views: 1688
Reputation: 370879
The .get
will return a function, so if you want to run the function, you must invoke it:
this.keyBinding.get('Backspace')();
If the string being passed in may not exist in the Map, check that it exists first:
const fn = this.keyBinding.get('Backspace');
if (fn) fn();
If the handleBackspace
and handleDelete
methods depend on having a this
context, then you'll need to account for that as well:
this.keyBinding
.set('Backspace', () => this.handleBackspace())
.set('Delete', () => this.handleDelete());
Upvotes: 2