首页 > 解决方案 > Typescript 类方法作为属性找到

问题描述

我的打字稿代码有一个小错误(?)。请参阅以下内容:

class Component {
    assertBoolean(): boolean {
       return true;
    }
}

class DummyComponent extends Component() {
}

const components: Component[] = [ DummyComponent ];

我收到以下打字稿错误:

错误 TS2322:类型 'typeof DummyComopnent' 不可分配给类型 'Component' 类型 'typeof DummyComponent' 中缺少属性 'assertBoolean'。

我真的不知道我在那里做错了什么,基本的OOP。

标签: typescript

解决方案


您没有实例化该类。DummyComponent在表达式中使用时表示类本身,而不是类的实例。要实例化您需要使用new运算符的类:

class Component {
    assertBoolean(): boolean {
    return true;
    }
}

class DummyComponent extends Component {
}

const components: Component[] = [ new DummyComponent() ];

要保留您需要使用的类的数组typeof Component。这表示类的类型(不是类的实例)

const components: (typeof Component)[] = [DummyComponent];
new components[0]()

推荐阅读