phaser
phaser copied to clipboard
Typescript: Possible type error for the returned value of a GameObject get corner function
Version
-
Phaser Version: v3.60.0
-
Operating system: Windows 10
Description
I'm using phaser with typescript.
When using one of the functions to get a corner of a GameObject (e.g. Images), the returned value type has the x and y position properties as optional. I'm uncertain if this is the intended behavior.
The getLeftCenter()
's returned value is typed as Phaser.Types.Math.Vector2Like
, whose values are optional. To satisfy typescript, I use the optional out
parameter of these functions like so:
const centerReference = { x: 0, y: 0 }
this.getCenter(centerReference)
Example Test Code
// Typescript complains that v.x is possibly undefined
const v: Phaser.Types.Math.Vector2Like = { x: 0, y: 0 }
const x = v.x + 1
// Same as above, we get a type error for imgCenter.y
const img = this.add.image(0, 0, "cane")
const imgCenter = img.getCenter()
const y = imgCenter.y + 1
Additional Information
As an interesting behavior, the returned type is not a Phaser.Types.Math.Vector2Like
if you provide the out
parameter.
https://github.com/photonstorm/phaser/assets/54607854/a9b2b806-c207-4f29-bf62-2bfb2d02e18d
Example code:
// Now here, typescript does not complain
const img = this.add.image(0, 0, "cane")
const out = {x: 0, y: 0}
const imgCenter = img.getCenter(out)
const y = imgCenter.y + 1
I agree – the optionality here makes coding more difficult.
Vector2Like
type rather should not have fields marked as optional:
type Vector2Like = {
/**
* The x component.
*/
x?: number; // ⚠️ no optional?
/**
* The y component.
*/
y?: number; // ⚠️ no optional?
};
In the implementation using it (i.e. getTopLeft()), methods create an instance of Vector2 which has always props x
and y
If it is required for another cases, maybe should introduce new type for that purpose explicitly?
Thank you for submitting this issue. We have fixed this and the fix has been pushed to the master
branch. It will be part of the next release. If you get time to build and test it for yourself we would appreciate that.