phaser icon indicating copy to clipboard operation
phaser copied to clipboard

Add generic types to setData()

Open florestankorp opened this issue 2 years ago • 0 comments

The problem: At the moment Phaser.GameObjects.GameObject.setData() is typed as follows:

setData(key: string | object, data?: any): this;

This results in situations that might be undesirable and prone to errors

image

A possible solution: By adding generic types to the setData method developers can make sure they only pass in the intended values like so:

  1. First we modify the type definition phaser.d.ts
setData<T>(key: string | T, data?: T): this;
  1. Then we define an interface for the data we want to pass to our GameObject
export interface ParallaxSettings {
    target: number;
    speed: number;
}
  1. Now we can pass a type to out data and make sure it only accepts the desired type
sprites.dreamer.setData<ParallaxSettings>({
    target: 156,
    speed: 0.4,
});

TypeScript throws an error

image

image

Backwards compatibility Just use any 👍

image

[Optional] Do you want to help provide this feature?

Sure. Let me know if this is something that would help the project and I can submit a PR...

florestankorp avatar Jun 10 '22 18:06 florestankorp