【问题标题】:Typescript class method found as propertyTypescript 类方法作为属性找到
【发布时间】:2019-01-17 10:45:55
【问题描述】:

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

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

class DummyComponent extends Component() {
}

const components: Component[] = [ DummyComponent ];

我收到以下打字稿错误:

错误 TS2322:类型“typeof DummyComopnent”不可分配给类型 类型“typeof”中缺少“组件”属性“assertBoolean” 虚拟组件'。

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

【问题讨论】:

标签: typescript


【解决方案1】:

您没有实例化该类。 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]()

【讨论】:

  • 似乎合法。我这样做是因为实例化将由我正在使用的框架(Angular)执行。我会坚持使用any 类型。谢谢!
  • @ChainList 避免任何。添加了一个关于如何在数组中保留类的版本:)
  • 我不知道,谢谢你的回答!事实上,我想避免使用any
猜你喜欢
  • 2020-08-16
  • 2019-03-31
  • 2021-05-31
  • 2013-10-15
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
相关资源
最近更新 更多