phaser
phaser copied to clipboard
Add generic types to setData()
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
A possible solution:
By adding generic types to the setData
method developers can make sure they only pass in the intended values like so:
- First we modify the type definition phaser.d.ts
setData<T>(key: string | T, data?: T): this;
- Then we define an interface for the data we want to pass to our GameObject
export interface ParallaxSettings {
target: number;
speed: number;
}
- 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
Backwards compatibility
Just use any
👍
[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...