TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. The snippet below demonstrates simple usage of Google Maps using TypeScript.
let map: google.maps.Map;
const center: google.maps.LatLngLiteral = {lat: 30, lng: -110};
function initMap(): void {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center,
zoom: 8
});
}
Getting Started
The DefinitelyTyped project is an open source projects that maintains type declaration files for many packages including Google Maps. The Google Maps JavaScript declaration files (see source files on GitHub) can be installed using NPM.
npm i -D @types/google.maps
Alpha and Beta Features
The types typically do not have the properties, functions, or classes found in alpha or beta releases. In many of these cases, the object can be cast to the correct type.
The following error is caused by the mapId
beta property for MapOptions
.
error TS2345: Argument of type '{ center: google.maps.LatLng; zoom: number; mapId: string; }' is not assignable to parameter of type 'MapOptions'. Object literal may only specify known properties, and 'mapId' does not exist in type 'MapOptions'.
The above error can be corrected with the cast below.
{ center: {lat: 30, lng: -110}, zoom: 8, mapId: '1234' } as google.maps.MapOptions
Configuration (Optional)
After installing the declaration files, the TypeScript compiler may require additional configuration using one of the following methods.
Compiler Options in tsconfig.json
It is recommended to use compilerOptions.types
field in tsconfig.json
at the
root of the project. See the TypeScript
documentation
for more configuration options.
{
"compilerOptions": {
"types": ["google.maps"]
}
}
Module Import
An alternative is to use an empty import to inform the compiler about the types.
import {} from 'google.maps';
An error similar to the following may be generated.
@types/google.maps/index.d.ts is not a module
The solution is to create an index.d.ts
at the project root declaring the
google.maps
module.
declare module 'google.maps';
Triple Slash directive
Triple-slash directives are single-line comments containing a single XML tag. The contents of the comment are used as compiler directives.
The following comment can be added to the TypeScript file to reference the Google Maps declarations.
/// <reference types="google.maps" />