Search code examples
typescripttypestypeerrorphaser-frameworkbrunch

How can I explicitly declare a variable of some Phaser type?


I am attempting to use Phaser with Brunch and TypeScript using samme's brunch-phaser2 skeleton, but I am running into a TypeError:

$ git clone https://github.com/samme/brunch-phaser2.git --branch typescript
$ cd brunch-phaser2
$ npm install
$ npm run start

> [email protected] start /home/sam/github/samme/brunch-phaser2
> brunch watch --server

13:49:11 - info: application started on http://localhost:3333/
13:49:12 - error: Compiling of app/initialize.ts failed. TypeError: Cannot read property 'length' of undefined
Stack trace was suppressed. Run with `LOGGY_STACKS=1` to see the trace. 
13:49:12 - info: compiled 5 files into 2 files, copied 3 in 1.5 sec

A slightly different TypeError appears in my Phaser experimention repo when I add an explicit type to my game variable:

$ git clone https://github.com/samestep/phaser-nonsense.git --branch type-error
$ cd phaser-nonsense
$ npm install
$ npm run start

> @ start /home/sam/github/samestep/phaser-nonsense
> brunch watch --server

13:56:42 - info: application started on http://localhost:3333/
13:56:42 - error: Compiling of app/initialize.ts failed. Error: Error 2503: Cannot find namespace 'Phaser'. (Line: 3, Col: 13)
Stack trace was suppressed. Run with `LOGGY_STACKS=1` to see the trace. 
13:56:42 - info: compiled 2 files into vendor.js, copied index.html in 1.3 sec

But in either case, when I change this:

const game: Phaser.Game = new Phaser.Game({});

to this:

const game = new Phaser.Game({});

the TypeError goes away.

Why does this explicit type declaration cause a TypeError to occur, and how can I resolve the error without removing the explicit type declaration?


Solution

  • The Brunch TypeScript plugin doesn't support proper resolution of references (documentation). Their recommendation is to add plugins: { brunchTypescript: { ignoreErrors: true } } to your brunch-config.js and separately run tsc --noEmit -p . to check for errors.