如何动态地向类添加方法? [英] How to dynamically add methods to a class?

查看:90
本文介绍了如何动态地向类添加方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的一个归结示例失败,错误

assignment of computed property/element. Indexable signature not found

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

解决方案

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);
  }
});

尝试.

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

/* @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;
});

尝试.

Here's a boiled down example that fail with the error

assignment of computed property/element. Indexable signature not found

Surely flow can read the types and strings in the methods array. Why is it complaining?

解决方案

Flow doesn't seem to allow indexable properties on custom class definitions. I don't know why, though.

AFAIK you have two workarounds:

Extend your class by Object explicitly.

/* @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.

Or declare an indexable signature in an interface.

/* @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.

这篇关于如何动态地向类添加方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆