【问题标题】:Flowtype: How to use compute method in ClassFlowtype:如何在类中使用计算方法
【发布时间】:2018-05-14 10:46:43
【问题描述】:

我想根据参数访问类属性,代码如下:

class Commander {
  constructor() {}
  create() {}
  test() {}
  undo() {}
  redo() {}
  execute(...args): void {
    const command: string = args.slice(0);
    const rest: any[] = args.slice(1);
    this[command].apply(this, rest);
  }
}

但我收到如下错误:

无法获取this[command],因为Commander 1 中缺少索引器属性。

更多信息请看flowtype try

如果我做了一些愚蠢的事情,请告诉我!

谢谢!!

【问题讨论】:

    标签: flowtype flow-typed


    【解决方案1】:

    谢谢你的回答,但我想让代码保持整洁,我找到了另一个解决方案Try。但是使用 any 关键字,使检查对静态检查毫无意义。 – 辛

    如果您使用的任何关键字与仅针对任何涉及该变量的内容关闭流程相同。

    “如果你想选择不使用类型检查器的方法,any 就是这样做的方法。使用 any 是完全不安全的,应尽可能避免。”来自Any

    这是一种更安全的方式:(Try)

    class Commander {
      $key: "create" | "test" | "undo" | "redo";
      $value: () => mixed
      constructor() {}
      create() {}
      test() {}
      undo() {}
      redo() {}
      execute(command, ...rest): void {
        this[command].apply(this, rest);
      }
    }
    

    【讨论】:

      【解决方案2】:

      因为您使用的property accessor 可以是任何字符串,Flow 认为您正在尝试使用您的class instance as a map。为了解决这个问题,您需要在调用实例方法之前对command 变量进行某种检查。这是我建议的方法:

      (Try)

      class Commander {
        constructor() {}
        create() {}
        test() {}
        undo() {}
        redo() {}
        execute(...args): void {
          const command: string = args.slice(0);
          const rest: any[] = args.slice(1);
          switch(command) {
            case "test":
              this.test.apply(this, rest);
              break;
            case "undo":
              this.undo.apply(this, rest);
              break;
            case "redo":
              this.redo.apply(this, rest);
              break;
            default:
              throw new Error("Invalid command");
          }
        }
      }
      

      您还可以将 method.apply(this, rest) 语法替换为 method(...rest) 以使内容更简洁,但这是文体,与您的问题不太相关。

      【讨论】:

      • 谢谢你的回答,但我想让代码保持整洁,我找到了另一个解决方案Try。但是使用 any 关键字,让检查对静态检查毫无意义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多