Search code examples
typescripttsc

typescript compiler error: Cannot convert '{}[]' to 'Array'


I'm having compiler errors with this typescript code:)

I've defined playerBullets like so:

playerBullets: Array = Array[40];

and try to do this:

this.playerBullets = this.playerBullets.filter(function (bullet) {
    return bullet.active;
});

but this code has been market with red syntax errors:

WebUI/ts/game.ts(89,19): Expected var, class, interface, or module WebUI/ts/game.ts(88,29): Cannot convert '{}[]' to 'Array'

If I change the definition to this:

playerBullets  = [];

it works, any ideas?


Solution

  • You need to define the array like this:

    playerBullets: bullet[] = new Array(40);
    

    And the overall code will look like this:

    interface bullet{
         active :bool;
    }
    
    var playerBullets:bullet[] = new Array(40)
    
    playerBullets = playerBullets.filter( function (bullet) {
        return bullet.active;
    });
    

    Of course you don't have to define the bullet type (but if you use typescript you probably want)

    var playerBullets:any = new Array(40)
    
    playerBullets = playerBullets.filter( function (bullet) {
        return bullet.active;
    });