使用 Typescript 上的函数映射字符串

Map a string with a function on Typescript

是否可以使用 TS 将字符串映射到函数。 例如:

this.keyBinding = new Map<string, Function>();
    this.keyBinding
        .set('Backspace', this.handleBackspace)
        .set('Delete', this.handleDelete)

我尝试使用以下方式执行它:

this.keyBinding.get('Backspace');

但是没有任何反应。

.get会return一个函数,所以如果你想运行这个函数,你必须调用它:

this.keyBinding.get('Backspace')();

如果传入的字符串在Map中可能不存在,请先检查是否存在:

const fn = this.keyBinding.get('Backspace');
if (fn) fn();

如果 handleBackspacehandleDelete 方法依赖于 this 上下文,那么您也需要考虑到这一点:

this.keyBinding
        .set('Backspace', () => this.handleBackspace())
        .set('Delete', () => this.handleDelete());