Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: How to pass null to an overloaded function in versions after 0.8.0.0?

Updated TypeScript from 0.8.0.0 to 0.8.1.1 today. The TS compiler now complains about passing null or undefined to a function/method that is overloaded.

For example, the google maps Marker class has a setMap method with 2 overloads. This is taken from the google maps definition file in the Definitely Typed project:

declare module google.maps {
    ...
    export class Marker extends MVCObject {
        ...
        setMap(map: Map): void;
        setMap(map: StreetViewPanorama): void;
        ...
    }
    ...
}

According to the google maps API v3 docs, to remove a marker from a map, you should set its map to null. I previously had this with TS 0.8.0.0 and it worked fine:

var someMarker: google.maps.Marker = (code to initialize marker);
...
someMarker.setMap(null);

TypeScript 0.8.1.1 complains about this with the message:

Ambiguous call expression - could not choose overload.

One fix I tried that did not work was trying to coerce TS into believing null was a reference to a google.maps.Map. This is apparently incorrect syntax, as the compiler complains it expects a ; where the ) is.

someMarker.setMap(null: google.maps.Map);

Here is the fix I have now, which seems to work. Is this the right way to work around this issue?

var nullMap: google.maps.Map = null;
someMarker.setMap(nullMap);

I realize another fix could be to modify the google maps TS definition file to allow an overload of setMap(map: any): void;, but that seems like a bad solution. Is there any other way currently, or planned in future TS builds, to work around this?

like image 902
danludwig Avatar asked Dec 08 '25 21:12

danludwig


1 Answers

The way you are working around it now works, but is more verbose than necessary.

You can specify that you mean null to be of the type google.maps.Map by casting it as such.

someMarker.setMap(<google.maps.Map>null);
like image 133
Peter Olson Avatar answered Dec 11 '25 15:12

Peter Olson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!