我有一个基类,Component:
module abc {
export class Component {}
}
我还有各种类扩展这个基类:
module cde {
export class Position extends abc.Component {}
}
现在,有一个实体类几乎只包含组件:
module abc {
export class Entity {
add(component: Component) {}
}
}
为什么我不能这样做:
var entity = new abc.Entity().add(new cde.Position());
编译器抱怨Argument types do not match parameters
,即使我的Position类扩展了Component类,这是add方法期望的类型......
将其更改为
var entity = new abc.Entity().add(<abc.Component>new cde.Position());
满足编译器错误,但我不明白为什么我需要明确地向下转发...
在阅读Breeze的回答后,我拿出了我的实际代码,剪掉了不相关的部分,并将其粘贴到游乐场......低,看看代码实际上是有效的。也许这是IntelliJ实现打字稿的问题?我会继续调查。
答案 0 :(得分:1)
我尝试了以下代码:
module moduleA {
export class classA {}
}
module moduleB {
export class classB extends moduleA.classA {}
}
module moduleA {
export class classC {
add(m: classA) {}
}
}
var c = new moduleA.classC();
c.add(new moduleB.classB());
编译器不会抱怨...
两个问题, 您使用的是哪个版本的编译器? 这是您的确切代码吗? (因为你的add方法没有返回任何内容,但是你将它分配给'var entity')