在 Flow 0.34 中定义自定义的“toString”

Defining a custom `toString` in Flow 0.34

我有一些功能想要自定义 toString 属性,像这样:

var Foo = function () {};
Foo.prototype.toString = function () { return 'hi'; };

Here's a live example of the code.

在 Flow 0.33 中它可以正常工作,但在 Flow 0.34 中它会产生错误:

4: Foo.prototype.toString = function () { return 'hi'; };
   ^ Object. Covariant property `toString` incompatible with contravariant use in
4: Foo.prototype.toString = function () { return 'hi'; };
   ^ assignment of property `toString`

这是我的代码或 Flow 中的错误吗?

虽然 Flow 对这种 class 声明样式的支持有限,但我强烈建议使用 ES6 语法。一次性声明风格帮助Flow更容易理解代码。

class Foo {
  toString() {
    return 'hi';
  }
}

您可以使用 any 类型转换解决协方差约束:

(Foo.prototype : any).toString = function () { return 'hi'; };

您的代码没有错,流程只是强制执行特定的样式。

一种超级愚蠢的方法(欺骗转译器;尽可能避免):

Object.assign(Utils, { ['to'+'String']: (s/*:any*/)/*:string*/ => ''+ s });

我更喜欢上面最佳答案中的任意转换示例。

(Utils/*:any*/).toString = (s/*:any*/)/*:string*/ => ''+ s;

但是,我也需要这个,(如果你更改方法签名,当你去调用它时):

Utils.stringEquals = (a/*:any*/,b/*:any*/)/*:%checks*/ =>
    (Utils/*:any*/).toString(a) === (Utils/*:any*/).toString(b);