Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi @toji 👋
I came across a bug in
maplibre-glthat was due to a cast to make the types work nicely withgl-matrix.It made me look at
gl-matrixto see if I could improve its types. I saw some pain points and made an implementation to address these.These are the changes I made:
glMatrix.ARRAY_TYPEInfer return type of gl-matrix methods from its inputs
In the snippet above
vectoris typed asvec3orIndexedCollection | [number, number, number], while it can safely be inferred that the result will be[number,number,number]based on its inputs.I introduced two type-only namespaces
TupleandReturnType.Tuplecollects all of the related tuples:Tuple.Vec3ReturnTypecollects all of the return types of the gl-matrix methods:ReturnType.Vec3<T>This way we can return as narrow as possible:
sadly typescript does not provide built-in support for defining the length of a typed array type (e.g.
Float32Array<{ length: 3 }>) otherwise we could provide even narrower support.Add overridable type for typing
glMatrix.ARRAY_TYPESeveral
gl-matrixmethods create an array type based on the variableglMatrix.ARRAY_TYPE, for examplevec3.create(). These functions currently return their respective wide type: for examplevec3.create()returnsvec3or[number, number, number] | IndexedCollection.glMatrix.ARRAY_TYPEis by default set totypeof Float32Array !== "undefined" ? Float32Array : Array. This can be overwritten by the user, but there is no way for them to control the type.I implemented this via module augmentation.
Conclusion
By implementing these changes and testing them out in the
maplibre-glcodebase I was able to reveal several dodgy types, so I think there is merit to the code.Open for discussion/feedback/...