I'm making a game with Phaser 3, TypeScript and Parcel. I have added some classes that implement some interfaces but the interfaces import and use each other. I started using eslint with airbnb ruleset. One of the rules they implement is import/no-cycle But I feel like my game needs it.
import { Scene } from 'phaser';
import PlayerInterface from '../../entities/player/PlayerInterface'; // circular
interface GameInterface extends Scene {
player: PlayerInterface;
}
export default GameInterface;
import GameInterface from '../../scenes/game/GameInterface'; // circular
interface PlayerInterface extends Phaser.Physics.Arcade.Sprite {
scene: GameInterface;
speed: number;
}
export default PlayerInterface;
A "Player" is added to the "Game" and the Player Class has a scene. So they both need to be in the interface. Since this is only a type file can I ignore this rule? Or is there a cleaver restructure I can do?
Additionally here is a link to the full repo.
Here are the 2 classes that implement these interfaces.
class Game extends Scene implements GameInterface {
player: PlayerInterface;
constructor() {
super({
key: 'Game',
});
}
preload(): void {
/* preload code */
}
create(): void {
/* create code */
}
}
class Player extends Phaser.Physics.Arcade.Sprite implements PlayerInterface {
scene: GameInterface;
constructor(scene: GameInterface) {
super(scene, x, y, 'player');
this.scene = scene;
this.scene.add.existing(this);
this.scene.physics.add.existing(this);
}
static preload(scene: GameInterface): void {
/* preload */
}
}
As you can see the game class creates the player, but the player is also passed a scene when created.
firs of all Circular Dependency means when you have two class A & B:
A uses class B, so A is depended on BB uses class A, so the B is depended on A tooAs the result, on initialing both classes it goes throw an infinite loop because it wants to create class A based on B, and class wants to be created based on class A though it went to benefit loop.

So just cut the unnecessary dependency.
Game class, it seems you didn't need to use PlayerInterface.Scene and Phaser.Physics.Arcade.Sprite in your interfaces. Because you are extending them in your concrete classes already. Just remove them.Place both Interfaces in the same file. This will get ride of the circular file loading which is what is tripping you up here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With