javascript - 在 Typescript 中从外部库扩展原型(prototype)

标签 javascript typescript module typescript1.8 typescript-typings

我想在 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/

相关文章:

javascript - Navigator.webkitPersistentStorage 在 TypeScript 中的使用

node.js - Promise 返回未定义和之后的数据

typescript - 如何在 typeorm 中组合 3 列,postgres 是唯一的?

python - 如何在Python模块初始化时启用日志记录?

visual-studio - Visual Studio 模块负载限制?

javascript - 如何隐藏使用 !important 的 CSS 背景图片

javascript - 冒泡事件从基类向下传递到子类

javascript - dotdotdot 在 flexslider 中显示 ... 之后的额外文本

javascript - 在javascript中读取本地csv文件?

node.js - nodejs 从 import 转换为 require