【发布时间】:2018-03-23 10:48:50
【问题描述】:
我正在使用打字稿并遇到这样的问题。我有一个类列表和它的实例数组。这些类从一些基本类扩展而来。每个类都有自己的方法。我想在数组元素上调用这些自己的方法。但是我有一个错误。
这是example:
class BasicClass {
getName() {
console.log('My name is BasicClass');
}
}
class Child1 extends BasicClass {
getChildOneSpecialName() {
console.log('My getChildOneSpecialName is Child1');
}
}
class Child2 extends BasicClass {
getSpecialName() {
console.log('My special name is Child2');
}
}
class Child3 extends BasicClass {
getStrangeName() {
console.log('My getStrangeName is Child1');
}
}
const array = [new Child1(), new Child2(), new Child3()];
array[1].getSpecialName(); // Property 'getSpecialName' does not exist on type 'Child1 | Child2 | Child3'.
array[2].getStrangeName(); // Property 'getStrangeName' does not exist on type 'Child1 | Child2 | Child3'.
我应该怎么做才能使它成为可能?
【问题讨论】:
-
欢迎来到 Stack Overflow!您问题的全部内容必须在您的问题中in,而不仅仅是链接。链接腐烂,使问题及其答案对未来的人们毫无用处,人们不应该离开现场来帮助你。在问题中添加minimal reproducible example ,最好使用 Stack Snippets(
<>工具栏按钮)使其可运行(here's how to do one)。更多:How do I ask a good question?(但遗憾的是,sn-ps 没有对 TypeScript 的内置支持。) -
这次我已将代码复制到问题中。
标签: javascript typescript oop ecmascript-6 typing