How to extend a class in Typescript that loads dynamically

I am using the Google Javas API with the namespace google.mapsthrough npm install @types/googlemaps. I believe the API loads dynamically, so google.mapsJS global is not available right away.

But I don’t understand why I get a runtime error: Uncaught ReferenceError: google is not definedwhen I try to expand google.maps.Markerwith class, but notinterface

// No problem!
export interface UuidMarker extends google.maps.Marker {
  uuid: string;
}

// Uncaught ReferenceError: google is not defined!!
export class UuidMarker0 extends google.maps.Marker {
  uuid: string;
  constructor(uuid: string, options?: gmMarkerOptions) {
    super(options);
    this.uuid = uuid;
  }
}

An alternative approach using only the interface

// this works
export function UuidMarkerFactory(uuid: string, marker: google.maps.Marker): google.maps.Marker & {uuid:string} {  
  return Object.assign(marker, {uuid});
}

// this fails with google is not defined!! 
export function UuidMarkerFactory0(uuid: string, options?: any): google.maps.Marker & {uuid:string} {
  if (typeof google == "undefined") return null
  return Object.assign(new google.maps.Marker(options), {uuid});
}

What is the best practice for extending a dynamically loadable class?

Additional Information

ionic2@RC0, rollup . typescript node_modules main.js script . API Google angular2-google-maps script.

interface ( typescript "friendly" ), , UuidMarker?

+4
1

, google.maps, @types.

, , google.maps, google.maps.Marker.

, , google.maps .

UuidMarker, .
javascript, typescript js.


, .
, , google maps:

interface UuidMarker extends google.maps.Marker {
    uuid: string;
}

let UuidMarker0: { new (uuid: string, options?: gmMarkerOptions): UuidMarker };

function classLoader() {
    UuidMarker0 = class UuidMarker0 extends google.maps.Marker implements UuidMarker {
        uuid: string;

        constructor(uuid: string, options?: gmMarkerOptions) {
            super(options);
            this.uuid = uuid;
        }
    }
}

( , )

:

function UuidMarker(uuid: string, marker: google.maps.Marker): google.maps.Marker & { uuid: string } {
    return Object.assign(marker, { uuid });
}

:

type MyType = google.maps.Marker & { uuid: string };

, , MyType , google.maps.Marker uuid.

:

interface Point {
    x: number;
    y: number;
}

type Point3D = Point & { z: number };

let p1: Point = { x: 0, y: 0 };
let p2: Point3D = { x: 0, y: 0, z: 0 };
+6

Source: https://habr.com/ru/post/1659384/


All Articles