简体   繁体   English

将对象成员分配给上下文菜单命令-TypeScript

[英]Assign object members to context menu command - TypeScript

I need to replace string in JSON to functions (object methods) with the corresponding name and pass an argument to it but got 我需要将JSON中的字符串替换为具有相应名称的函数(对象方法),并将参数传递给它,但得到

"Type 'this[Extract<keyof this, string>]' is not assignable to type '(event?: any) => void'"

In short, would like to have something like: 简而言之,想拥有这样的东西:

 if (typeof this[key] === 'function') { position.command = this[key]; } 

But my solution does not let me pass arguments to it 但是我的解决方案不允许我将参数传递给它

Try this. 尝试这个。 Also note that this is dangerous since every function will be assigned to command on this. 另请注意,这样做很危险,因为每个功能都将分配给该命令。

  id = 1;
  name = 'alice';

  position = {
    command: null
  }

  ngOnInit() {
    for (const key in this) {
      console.log(key);

      if (typeof this[key] === 'function') {
          this.position.command = this[key];
      }
    }
  }

  someFunction() {
    console.log('someFunction');
  }

See this stackblitz it doesn't give any error. 看到这个堆叠闪电,它没有给出任何错误。

Error is only there if you initialize command with a string; 仅当您使用字符串初始化命令时,错误才存在; eg. 例如。 command: ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM