接口为类型的数组(具有接口的多态性)

齐夫·格拉泽(Ziv Glazer)

我正在尝试创建一个对象数组,其中所有对象都实现接口Foo。这是一个简化的示例来说明此问题:

interface Foo {
    fooAction(): any;
}

class Bar implements Foo
{
     public fooAction() {
          return "nothing important";
      }
 }

 let arrayThatINeed : Foo[] = [Bar]; // Type error: Type Bar[] is not 
                                     // assigable to type 'Foo[]'

不应该支持这种行为吗?如果没有,那么编码这种行为的替代方法有哪些?

尼桑·托默尔

您正在将类添加到数组中,而不是该类的实例。
应该:

let arrayThatINeed : Foo[] = [new Bar()];

这也将起作用:

let arrayThatINeed : Foo[] = [{
    fooAction: () => { console.log("yo"); }
}];

编辑

我不是有角度的开发人员,所以我不能与之相关,但是如果我对您的理解正确,那么您需要一个类数组而不是实例,这在JavaScript中意味着您需要一个构造函数数组。

在打字稿中很容易做到:

interface FooConstructor {
    new (): Foo;
}

interface Foo {
    fooAction(): any;
}

class Bar implements Foo {
    public fooAction() {
        return "nothing important";
    }
}

let arrayThatINeed : FooConstructor[] = [Bar];

您会看到此代码不会导致错误,但是也不正确,因为即使您implementsBar类中删除了该部分也不会抱怨
我可以找到导致这种情况的原因,但我认为编译器仍应对此抱怨。

如果您要Foo上课,可以解决此问题,例如:

interface FooConstructor {
    new (): Foo;
}

abstract class Foo {
    abstract fooAction(): any;
    fn() {}
}

class Bar extends Foo {
    public fooAction() {
        return "nothing important";
    }
}

let arrayThatINeed : FooConstructor[] = [Bar];

现在,如果您extends从中删除零件,Bar您将得到一个错误。
但是您必须至少有一个非抽象的方法/成员Foo才能起作用(也就是说,如果数组中的内容不是扩展类,它将抱怨Foo)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章