[Solved: neither] Phaser & Typescript - Casting the Game or?

Update: You can ignore this thread. I came up with a solution where I capture the appropriately annotated game in a lambda and use that in the callback rather than providing the game from the scene. Thanks samme for looking!


Hi all, long time dev, but new to TypeScript and Phaser. I have a subclassed Game, and then a callback in a Scene that needs to access the game instance. In JavaScript, this is as easy as scene.game, however I want to be able to call methods added to the Game.

My question is, is it better to cast scene.game or to store a reference to the game object with the subclassed type. I’m torn because casting seems gross, but so does keeping a reference that’s already kept. The same issue comes up with scenes (though generally I’ll be using events to avoid this.) Also, am I totally missing another even better option?

class MyGame extends Phaser.Game {
  myGameMethod() {
    // does something
  }
}

// Is this preferred
class MySceneA extends Phaser.Scene {
  myScneAMethod() {
    myGame = <MyGame>this.game;
    myGame.myMethod();
  }
}

// or is this better
class MySceneB extends Phaser.Scene {
  private _myGame : MyGame;
  constructor(myGame: MyGame) {
    _myGame = myGame;
  }

  mySceneBMethod() {
    _myGame.myGameMethod();
  }
}

I think you can do

class MySceneA extends Phaser.Scene {
  game: MyGame;
}

Do I need to assign that somehow? I tried adding that and it doesn’t just autocast. And TypeScript didn’t like “game = game” :slight_smile: Not quite sure if what you’re saying is different than what I do in MySceneB, or am I misunderstanding something.

I think just like this:

class MySceneA extends Phaser.Scene {
  game: MyGame;

  mySceneAMethod() {
    this.game.myMethod();
  }
}