I'm trying to use the @types/googlemaps
type definition file.
The code looks like
declare namespace google.maps {
/***** Map *****/
export class Map extends MVCObject {
constructor(mapDiv: Element|null, opts?: MapOptions);
fitBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void;
...
...
overlayMapTypes: MVCArray<MapType>;
}
export interface MapOptions {
backgroundColor?: string;
disableDoubleClickZoom?: boolean;
draggable?: boolean;
...
When I try to use this type definition in my project, like so
import * as google from 'googlemaps';
I get a compile error saying
Error:(2, 25) TS2306:File 'C:/Users/CodyB/musicappproj/src/node_modules/@types/googlemaps/index.d.ts' is not a module.
Why does it not consider this types definition file to be a module? Am I using it wrong ? Is the definition file wrong?
The compiler does not consider this type definition file to be an ECMA6 module because the file lacks a top-level export/import. Instead, the file nests/hides its exports inside a
namespace
and does not export the namespace. As a result, the namespace becomes part of the global scope, and the file does not become a module.A file is a module only if it has a top-level import or export. In the following code, both
foo.ts
andbar.ts
are modules, butbaz.ts
is not, because it lacks a top-levelimport
orexport
statement.Yes. You are treating the file like it is a module - which it is not. The alternative is to access its members through the global namespace it defines. Here are two approaches:
One is to 'dot into' the namespace like this:
Another is to use destructuring like this:
No. It is taking a valid approach albeit one that is arguably more conventional for a browser (e.g. Firefox) application than it is for a NodeJS application.
See also:
https://www.typescriptlang.org/docs/handbook/namespaces.html
https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html