到目前为止我设置了所有内容以使用带有requirejs的TypeScript。我用类测试了我的场景,一切正常,但是当我尝试使用接口定义时,我失败了。
IComponent.ts:
/// <reference path="Actor.ts" />
interface IComponent {
owner: Actor
init()
update(delta: number)
render()
}
Actor.ts:
/// <reference path="IComponent.ts" />
class Actor {
private components: IComponent[] = []
add(component: IComponent) {
component.owner = this;
this.components.push(component);
}
remove(component: IComponent) {
var index = this.components.indexOf(component);
this.components.splice(index, 1);
}
update(delta: number) {
this.components.forEach(c => c.update(delta));
}
render() {
this.components.forEach(c => c.render());
}
init() {
this.components.forEach(c => c.init());
}
}
export = Actor
我的IComponent.ts中出现错误:符号&#39; Actor&#39;无法找到。如何从界面中引用我的Actor类?
答案 0 :(得分:1)
目前看来,你有一个逻辑循环引用,Actor依赖于IComponent而IComponent依赖于Actor。
如果没有IComponent
课程,您的Actor
界面几乎无法使用,因此我建议的解决方案是将IComponent
界面放在actor.ts
文件中。这样,依赖性是自给自足的。
export interface IComponent {
owner: Actor;
init();
update(delta: number);
render();
}
export class Actor {
private components: IComponent[] = []
add(component: IComponent) {
component.owner = this;
this.components.push(component);
}
remove(component: IComponent) {
var index = this.components.indexOf(component);
this.components.splice(index, 1);
}
update(delta: number) {
this.components.forEach(c => c.update(delta));
}
render() {
this.components.forEach(c => c.render());
}
init() {
this.components.forEach(c => c.init());
}
}
或者,您可以使IComponent
取决于Actor
的抽象而不是具体类(在您的情况下,可能是IActor
。现在您的Actor
取决于在IComponent上,但那是链的末尾。
export interface IComponent {
owner: IActor;
init();
update(delta: number);
render();
}
export interface IActor {
add(component: IComponent);
remove(component: IComponent);
update(delta: number);
render();
init();
}
Hacky Fix:
这解决了IComponent.ts文件中的错误,但不是很好。
import Actor = require('actor');
interface IComponent {
owner: Actor;
init();
update(delta: number);
render();
}