Using generics in es6 Map with Typescript

Viewed 16183

I've got a project in Typescript 2.0 and I'm using es6 as my module, with the lib es2017 included so I can use maps. I've got everything working except I seem to need to do some unnecessary casts.

static readonly gameStateMap: Map<GameState, Phaser.State> = new Map([
    [GameState.PONG, new PongState() as Phaser.State],
    [GameState.BREAKOUT, new BreakoutState() as Phaser.State]
]);

Why do I need to cast them to Phaser.State? Since they both directly extend Phaser.State I thought I should be able to just stick them in the map with no problem.

I thought maybe I just needed to refine my generics declaration, so I tried:

Map<GameState, V extends Phaser.State>.

I see that syntax used in Typescript's generics docs.

But it doesn't work. Is this an ES6 generic and that's my problem? How can I fix this to not need to cast?

Also, this issue only occurs if the classes in question have different properties. The error is:

error TS2345: Argument of type '((GameState | PongState)[] | (GameState | BreakoutState)[])[]' is not assignable to parameter of type 'Iterable<[GameState, State]>'.
2 Answers
Related