英文:
how to add custom property and method to google map with TypeScript
问题
I wanna add properties like id
and label
to MVCObject
interface so that I can access those properties in Marker
or Overlay
, and add a method like isOpened
to the InfoWindow
interface so that every infoWindow
instance created by the InfoWindow
interface has that method.
在JavaScript中,我可以这样做:
marker.id = id
marker.label = label
google.maps.InfoWindow.prototype.isOpened = () => {}
但问题是,我不知道如何修改TypeScript以实现这一点。
我有两种解决方案,但都不太理想。
-
似乎我可以使用
MVCObject
中的get
和set
方法来添加属性,而无需修改TypeScript,但这不太理想,因为这种方法会忽略TypeScript。 -
修改
node_modules/@types/google.maps
也是我拥有的另一种解决方案,但我不知道直接更改node_modules
是否是一个好主意。
请告诉我如何更好地处理这个TypeScript问题。谢谢!
我正在使用 react
,@googlemaps/js-api-loader
和 @types/google.maps
。
英文:
I wanna add properties like id
and label
to MVCObject
interface so that I can access that properties in Marker
or Overlay
, and method like isOpened
to InfoWindow
interface so that every infoWindow
instance created by InfoWindow
interface have that method.
in JavaScript, I can do this like
marker.id = id
marker.label = label
google.maps.InfoWindow.prototype.isOpened = () => {}
but the problem I don't know how to modify TypeScript about this.
I have two solutions that don't look ideal.
-
It seems that I can add properties to
google.maps.MVCObject
interface without modifying TypeScript usingget
,set
method inMVCObject
, but it's not ideal because this way ignores TypeScript. -
Modifying
node_modules/@types/google.maps
is also another solution I have, but I don't know whether it's nice idea to directly changenode_modules
.
please let me know nicer ways to handle this TypeScript problem. thanks~!
I'm using react
, @googlemaps/js-api-loader
, and @types/google.maps
答案1
得分: 1
以下是翻译好的部分:
不建议向第三方库添加属性,因为您必须自己分配所有对象,您可以使用 Map
或 WeakMap
来记录该对象与您自己定义的属性之间的关系。
还有一种通过声明合并扩展包的定义的方法,创建一个像下面这样的 d.ts
文件:
declare module "<package_name_to_modify>" {
interface TheInterface {
// 在这里添加您想要的内容
}
}
export {}
请注意,对于 type
不起作用,因为它不能合并。
如果您坚持要修改定义(或者它是一个 type
)并且正在使用 yarn
作为包管理器,您可以尝试 yarn patch 命令,它将创建一个临时包,可以根据您的要求进行修改。并记得按照说明保存这些更改。
英文:
It not a good idea that to add properties to third-party library since you have to assign all object by your self, you could use Map
or WeakMap
to record the relationship of that object and properties defined by yourself.
And there is a way to extends the definition of package by declaration merging, create a d.ts
file like the following:
declare module "<package_name_to_modify>" {
interface TheInterface {
// add what you want here
}
}
export {}
Note that it won't works for type
since it can not be merged.
If you insist to modify the definition (or it is a type
) and you are using yarn
as package manager, you could try yarn patch command, it will create a temporary package that can modify as you want. And remember to follow the instruction to save those changes
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论