找到作为属性的Typescript类方法

Cha*_*ist 1 typescript

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

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

class DummyComponent extends Component() {
}

const components: Component[] = [ DummyComponent ];
Run Code Online (Sandbox Code Playgroud)

我收到以下打字稿错误:

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

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

Tit*_*mir 5

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

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

class DummyComponent extends Component {
}

const components: Component[] = [ new DummyComponent() ];
Run Code Online (Sandbox Code Playgroud)

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

const components: (typeof Component)[] = [DummyComponent];
new components[0]()
Run Code Online (Sandbox Code Playgroud)