我有很多遗留的 ES5 代码,它们不使用 class 关键字来定义“类”。我想用 Flow 进行注释和类型检查。这可能吗?
我只找到使用 class 关键字的示例: https://flowtype.org/docs/classes.html#_
最佳答案
由于 ES5“类”只是函数,因此您肯定可以为许多相同的检查添加类型注释
例如这个带有 Flow 的 ES6 类定义
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!';
};
尽管您确实错过了对名称进行额外的类属性检查。
我怀疑与您的问题更相关,您似乎可以通过使用构造函数名称作为类型注释来检查其他变量/参数等,看看它们是否与您的 ES5“类”匹配:
https://flowtype.org/docs/objects.html#constructor-functions-and-prototype-objects
编辑:是的,我只是天真地尝试添加这样的注释:
this.name: string = name;
但 flowtype 目前不喜欢这样。 除非有人更了解,否则我想唯一的解决方法是这样的
const tmpName: string = name;
this.name = tmpName;
尽管这显然不太好。
关于javascript - 你能用 Facebook 的 Flow 注释那些没有用 ES6 class 关键字定义的类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713201/