1

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.

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.