简体   繁体   English

Phaser + TypeScript 严格模式

[英]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.我正在 Phaser.io 开始我的冒险,我想在 TypeScript 中创建项目,以充分利用它的编译器。 By that I mean running TS in the strict mode.我的意思是在strict模式下运行 TS。 One of the advantages (for me) is the additional safety from nullable object.优点之一(对我而言)是可空对象的额外安全性。 And this is where it doesn't go well with Phaser.这就是它与 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.因此,建议创建一个可为空的player成员,然后为其分配值。 This is where TypeScript's strict mode shows error: Object is possibly 'null'.这是 TypeScript 的严格模式显示错误的地方: Object is possibly 'null'.

The best idea I had to deal with this situation is using monads like Maybe .我必须处理这种情况的最佳想法是使用像Maybe这样的 monad 。 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.所以我想知道,是否还有其他使用 Phaser 的模式或方法,这将使我能够在不使用 monad 的情况下启用严格模式。

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 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM