Crine Crine - 2 months ago 8x
TypeScript Question

Extending a prototype from an external library in Typescript

I would like to extend the prototype of an external library in Typescript (1.8). The external library in my case is google.maps for which I have included the Typescript Definition file from NuGet. Now I want to extend the prototype of the google.maps.LatLng by adding a distance function like so in a file "extensions.ts":

/// <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);

Then I want to use it:

import "./extensions.ts"

let p1 = new google.maps.LatLng(5, 5);
let p2 = new google.maps.LatLng(10, 10);


However this code does not work with many errors :/
What is the correct way of solving that? Extending the global declarations like Array or String works that way as mentioned here.

Note: For the resulting file to work you also have to include the google maps javascript library:

<script type="text/javascript" src="[your-key-here]&sensor=FALSE"></script>


You're almost there, it's just that you can't define an interface along with its namespace.
Should be:

declare global {
    module google.maps {
        interface LatLng {
            distanceTo(other: LatLng): number;

It compiles, but I haven't run it so I haven't checked for runtime problems.

Also, when you import do it without the .ts extension:

import "./extensions"