michael
michael

Reputation: 4547

Typescript: How do I use a class or interface from a namespace

I want to extend a class defined in the namespace google.maps in this file:

@types/googlemaps/index.d.ts

class MyMarker extends google.maps.Marker {
  constructor(options: google.maps.MarkerOptions){
    super(options);
  }
}

This transpiles without errors. But on runtime, I get an error in the constructor because the google.maps global is still undefined.

What am I doing wrong?

Upvotes: 1

Views: 397

Answers (2)

michael
michael

Reputation: 4547

BTW, my fallback is to use an interface instead of class and do a bunch of TS typecast gymnastics. It works but it's not optimal...

// new google.maps.Marker for MarkerClusterer
export interface UuidMarker extends Marker {
  uuid: string;
}

/**
 * Hack: "extend" google.maps.Marker to include uuid property
 *  guard with this.ready.then() to ensure google.maps is loaded
 */
function UuidMarkerFactory(uuid: string, options?: MarkerOptions) : Promise<UuidMarker> {
  return this.ready.then( ()=>{
    let gmOptions = options as any as google.maps.MarkerOptions;
    const marker = new google.maps.Marker( gmOptions );
    marker['uuid'] = uuid;
    return marker as any as UuidMarker;
  })
}

Upvotes: 0

luanped
luanped

Reputation: 3198

You need to import it first, for example

import Marker from 'googlemaps';

class MyMarker extends Marker 

Upvotes: 1

Related Questions