ngl icon indicating copy to clipboard operation
ngl copied to clipboard

Improve typing of "impostorable" buffers

Open luxaritas opened this issue 2 years ago • 4 comments

This PR allows instances of CylinderBuffer to be properly be typed as a CylinderGeometryBuffer | CylinderImpostorBuffer, as that's what the constructor returns.

FWIW: I'm not a fan of the as any casting as it avoids proper type checking. It might be preferable to change the API here to be a static method instead.

luxaritas avatar Jan 21 '22 18:01 luxaritas

Realized the same thing applies to hyperballstick and sphere, so adjusted those as well

luxaritas avatar Jan 21 '22 18:01 luxaritas

Thanks for noticing this. Could you describe, (the best would be a code example), the issue you were encountering? It looks to me that adding a supplementary dynamic constructor step in the code to solve an issue with static typings is adding a level of complexity that we may be able to avoid by other means (improving the static typings).

ppillot avatar Jan 23 '22 21:01 ppillot

The example would be if you have something like:

const buff = new CylinderBuffer(..., ...)

buff in this case would have no methods or attributes, as all the CylinderBuffer class has is a constructor - even though the constructor actually returns a CylinderGeometryBuffer | CylinderImpostorBuffer.

TypeScript doesn't allow for specifying a return type on a constructor, so the only alternative to this is creating a static method like CylinderBuffer.create() which could be properly typed. The reason I didn't do that is because that's a breaking API change - however I'd argue that's probably a more idiomatic way of doing it.

luxaritas avatar Jan 23 '22 21:01 luxaritas

Thanks for the clarification. I've played a bit with this and it looks like there are several problems here with regard to modelling this constructor in TS: parameters that are marginally incompatible, a conditional in the constructor that TS can't model.... I have tried to use the "old" JS objects constructor syntax (using function instead of class) but TS still chokes on types compatibility and it does not really improve the code.

ppillot avatar Jan 23 '22 22:01 ppillot