如何动态地向类添加方法?

时间:2017-11-04 14:41:48

标签: javascript flowtype

Here's a boiled down example因错误而失败

assignment of computed property/element. Indexable signature not found

当然,流可以读取methods数组中的类型和字符串。为什么抱怨?

1 个答案:

答案 0 :(得分:0)

Flow似乎不允许自定义类定义的可索引属性。但我不知道为什么。

AFAIK你有两个解决方法:

明确地将您的课程延长Object

/* @flow */

const methods: Array<string> = ['bar', 'baz'];

class Foo extends Object {}
//        ^^^^^^^^^^^^^^

methods.forEach((method: string) => {
  Foo.prototype[method] = function () {
    console.log('method', method);
  }
});

Try it

或在接口中声明可索引签名。

/* @flow */

interface Ix {
  [key: any]: any
}

class StrFunIx implements Ix {
  $key: string;
  $value: function;
}

class Foo extends StrFunIx {}

const methods: Array<string> = ['bar', 'baz'];

methods.forEach((method: string) => {
  Foo.prototype[method] = x => x;
});

Try it