你能用 Facebook 的 Flow 注释没有用 ES6 class 关键字定义的 classes 吗?

Can you annotate classes that are not defined with the ES6 class keyword with Facebook's Flow?

我有很多不使用 class 关键字来定义 "classes" 的遗留 ES5 代码。我想使用 Flow 进行注释和类型检查。这可能吗?

我只找到了使用 class 关键字的示例: https://flowtype.org/docs/classes.html#_

由于 ES5 "classes" 只是函数,您当然可以为许多相同的检查添加类型注释

例如这个 ES6 Class 定义与 Flow

class Hello {
  name: string;
  constructor(name: string) {
    this.name = name;
  }

  hello(): string {
    return 'Hello ' + this.name + '!';
  }

  static sayHelloAll(): string {
    return 'Hello everyone!';
  }
}

可以这样写:

function Hello(name: string) {
  this.name = name;
}

Hello.prototype.hello = function hello(): string {
  return 'Hello ' + this.name + '!';
};

Hello.sayHelloAll = function (): string {
  return 'Hello everyone!';
};

尽管您确实错过了额外的 class 属性 姓名检查。

我怀疑与你的问题更相关,看来你可以通过使用构造函数名称作为类型注释来检查其他 variables/arguments 等以查看它们是否与你的 ES5 "Class" 匹配:

https://flowtype.org/docs/objects.html#constructor-functions-and-prototype-objects

编辑:是的,我只是天真地尝试添加这样的注释:

this.name: string = name;

但 flowtype 目前不喜欢那样。 除非有人知道得更多,否则我想唯一的解决方法是

const tmpName: string = name;
this.name = tmpName;

虽然这显然不是很好