TypeScript 和 Google 地图

TypeScript 是 JavaScript 的类型化超集,可编译为纯 JavaScript。以下代码段展示了使用 TypeScript 实现 Google 地图的简易用法。

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
  });
}

开始使用

DefinitelyTyped 项目属于开源项目,用于维护众多软件包(包括 Google 地图)的类型声明文件。您可以使用 NPM 从 @types/google.maps 软件包中安装 Google Maps JavaScript 声明文件(可在 GitHub 上查看源文件)。

npm i -D @types/google.maps

Alpha 版和 Beta 版功能

这些类型通常不包含 Alpha 版或 Beta 版中的属性、函数或类。在诸多此类情况下,您可以将对象转换为正确类型。

以下错误是由 MapOptions 的 Beta 版属性 mapId 引起的。

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'.

您可以通过以下类型转换来纠正上述错误。

{ center: {lat: 30, lng: -110}, zoom: 8, mapId: '1234' } as google.maps.MapOptions

存在冲突的 @types 软件包

一些库可能会使用 @types/google.maps 以外的软件包,这可能会导致冲突。您可以使用 skipLibCheck 编译器选项来避免类型不一致的问题。

{
  "compilerOptions": {
    "skipLibCheck": true
  }
}

指定 typeRoots

一些框架(例如 Angular)可能需要指定 typeRoots 编译器选项,以包含通过 @types/google.maps 及所有其他“@types”软件包安装的类型。

{
    ...
    "compilerOptions": {
        ...
        "typeRoots": [
            "node_modules/@types",
        ],
        ...
    }
}