2

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

console.log(p1.distanceTo(p2))

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="http://maps.googleapis.com/maps/api/js?libraries=geometry&key=[your-key-here]&sensor=FALSE"></script>

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

1 Comment

I did the runtime test and it works. Thanks a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.