我想在 Typescript (1.8) 中扩展外部库的原型(prototype)。在我的例子中,外部库是 google.maps,我已为其添加了 NuGet 中的 Typescript 定义文件。 。现在我想通过在文件“extensions.ts”中添加距离函数来扩展 google.maps.LatLng 的原型(prototype):
/// <reference path="./google.maps.d.ts" />
export {}
declare global {
interface google.maps.LatLng {
distanceTo(google.maps.LatLng): number;
}
}
google.maps.LatLng.prototype.distanceTo = function(other) {
return google.maps.geometry.spherical.computeDistanceBetween(this, other);
}
然后我想使用它:
import "./extensions.ts"
let p1 = new google.maps.LatLng(5, 5);
let p2 = new google.maps.LatLng(10, 10);
console.log(p1.distanceTo(p2))
但是此代码无法正常工作,有很多错误:/ 解决这个问题的正确方法是什么?扩展全局声明(如数组或字符串)的工作方式如前面提到的 here .
注意:要使生成的文件正常工作,您还必须包含 google map javascript 库:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&key=[your-key-here]&sensor=FALSE"></script>
最佳答案
你已经快完成了,只是你不能定义一个接口(interface)及其命名空间。
应该是:
declare global {
module google.maps {
interface LatLng {
distanceTo(other: LatLng): number;
}
}
}
它可以编译,但我还没有运行它,所以我没有检查运行时问题。
此外,当您导入时,不要使用 .ts
扩展名:
import "./extensions"
关于javascript - 在 Typescript 中从外部库扩展原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38881605/