在打字稿中覆盖/重新声明具有泛型的类
目前我正在开发一个使用三个 js 和 typescript 的项目。我发现出于分组目的 Group 类。不幸的是 类型定义 Group
不带有像这样的泛型
meshGroup = new Group<Mesh>()
,其中 meshGroup.children
属性仅包含 网格
我尝试了这个
declare class MeshGroup extends Group {
children: Mesh[]
add(...object: Mesh[]): this
}
meshGroup = new MeshGroup()
,但得到了这个控制台
_classes_MeshGroup__WEBPACK_IMPORTED_MODULE_16__.MeshGroup is not a constructor
错误查找是否有一种简单的方法可以在打字稿中实现如此简单的包装器,但没有成功。
我的另一个解决方案是实现一个类型化数组
meshGroup: Mesh[] = []
并使其与类保持同步以处理类型,但它添加了另一层处理同步的层。
由于我不是使用打字稿的专家,是否有一个快速的类型定义技巧来实现这个“包装器”定义?
currently i am working on a project using three js and typescript. I have found out that for grouping purposes the Group class is recommended. Unfortunately the type definitions of Group
dont come with a generic like this
meshGroup = new Group<Mesh>()
of where the meshGroup.children
property only consists of Meshes
i tried this
declare class MeshGroup extends Group {
children: Mesh[]
add(...object: Mesh[]): this
}
meshGroup = new MeshGroup()
but got this console error
_classes_MeshGroup__WEBPACK_IMPORTED_MODULE_16__.MeshGroup is not a constructor
I looked up if theres an easy way to implement such simple wrapper in typescript but with no success.
My other solution would be to implement an typed array of
meshGroup: Mesh[] = []
and keep it in sync with the class to handle the types but it adds another layer of handling the sync.
Since i am not a pro at using typescript, is there a quick type definition trick to implement this "wrapper"-Definition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
When you call
group.children
you get an arrayObject3D[]
When you call
group.children
you get an arrayObject3D[]
as per the definition file. This is becauseGroup
could have otherGroup, Sprite, Line, Point, Mesh, etc.
inside it, so it defaults to the genericObject3D
. However, if you're sure it will only containMesh
es, you could simply nudge it with:编辑
它也有可能用类型更安全的类扩展
Group
类并调用父函数(装饰器模式):我的初始/旧答案
感谢您的回答@Marquizzo!
这绝对可以是一个解决方案。目前,我想出了另一种方法,通过 patch-package 覆盖包并编辑
Group.d.ts
文件如下:除了您的答案之外,我还获得了方法的类型安全性,这对我也很重要!
我不知道这是否最适合我未来的需求,但目前这解决了我的类型成瘾:D
EDIT
Its also kinda possible extending the
Group
class with a more type-safer class and calling the parent functions (decorator pattern):my initial/old answer
Thanks for the answer @Marquizzo!
That defenitely could be a solution. Currently i came up with another way with overriding the package via patch-package and edit the
Group.d.ts
file like this:In addition to your answer i also get type-safety on the methods which was important to me too!
I dont know if this fits the best for my needs in the future but currently this solves my type-addiction :D