【发布时间】:2016-08-11 04:18:49
【问题描述】:
我想在 Typescript (1.8) 中扩展一个外部库的原型。在我的例子中,外部库是 google.maps,我已经包含了来自NuGet 的 Typescript 定义文件。现在我想通过在文件“extensions.ts”中添加一个距离函数来扩展 google.maps.LatLng 的原型:
/// <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 提到的那样,扩展像 Array 或 String 这样的全局声明。
注意:要使生成的文件正常工作,您还必须包含 google maps javascript 库:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry&key=[your-key-here]&sensor=FALSE"></script>
【问题讨论】:
标签: javascript typescript module typescript1.8 typescript-typings