dotintegral
dotintegral

Reputation: 938

Phaser + TypeScript strict mode

I'm starting my adventure with Phaser.io and I wanted to create project in TypeScript that takes full advantage of it's compiler. By that I mean running TS in the strict mode. One of the advantages (for me) is the additional safety from nullable object. And this is where it doesn't go well with Phaser.

All of the examples I have seen till now suggest writing in the following pattern:

class MyScene extends Phaser.Scene {
  player: null;

  create() {
    this.player = this.physics.add.image(...)
  }

  update() {
    //...

    if (cursors.left.isDown) {
      this.player.setVelocity(-100)
    }
  }
}

So, creating a nullable player member and then assigning it's value is recommended. This is where TypeScript's strict mode shows error: Object is possibly 'null'.

The best idea I had to deal with this situation is using monads like Maybe. But that seems for me at this point like an overkill. So I wonder, if there are other patterns or ways of using Phaser, that would allow me to have the strict mode on without going as far as using monads.

Upvotes: 3

Views: 403

Answers (1)

Przemyslaw Jan Beigert
Przemyslaw Jan Beigert

Reputation: 2486

I think the best option will be just map type like

class X {
  player: Player | null = null;

  create() {
    this.player = new Player();
  }

  do() {
    (this.player as Player) / 2;
  }
}

Or use ! to skip initial property check

class X {
  player!: number;

  create() {
    this.player = 42;
  }

  do() {
    this.player / 2;
  }
}

playground

Upvotes: 1

Related Questions