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 地圖) 的類型宣告檔案。您可以使用 @types/google.maps 套件的 NPM,安裝 Google Maps JavaScript 宣告檔案 (請參閱 GitHub 上的來源檔案)。

npm i -D @types/google.maps

Alpha 版和 Beta 版功能

這些類型通常不含 Alpha 版或 Beta 版中的屬性、函式或類別。許多這類案例顯示,物件可以轉換為正確的類型。

下列錯誤是因 MapOptionsmapId Beta 版屬性所導致。

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

@type 套件發生衝突

部分程式庫可能會使用 @types/google.maps 以外的套件,因此可能會造成衝突。使用 skipLibCheck 編譯器選項,可避免類型不一致的問題。

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

指定 typeRoots

部分架構 (例如 Angular) 可能需要指定 typeRoots 編譯器選項,才能納入透過 @types/google.maps 和所有其他「@types」套件安裝的類型。

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