TypeScript 是 JavaScript 的類型化超集合,可編譯為純 JavaScript。以下程式碼範例示範採用 TypeScript 的 Google 地圖簡易用法:
TypeScript
async function init(): Promise<void> { // Import the needed libraries. await google.maps.importLibrary('maps'); // Access the map. const mapElement = document.querySelector('gmp-map')!; // Access the underlying map object. const innerMap = mapElement.innerMap; console.log({ mapElement, innerMap }); } void init();
JavaScript
async function init() { // Import the needed libraries. await google.maps.importLibrary('maps'); // Access the map. const mapElement = document.querySelector('gmp-map'); // Access the underlying map object. const innerMap = mapElement.innerMap; console.log({ mapElement, innerMap }); } void init();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<script>
// prettier-ignore
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "GOOGLE_MAPS_API_KEY"
});
</script>
</head>
<body>
<gmp-map center="-34.397,150.644" zoom="8" map-id="DEMO_MAP_ID">
</gmp-map>
</body>
</html>開始使用
DefinitelyTyped 是開放原始碼專案,可維護許多套件 (包括 Google 地圖) 的類型宣告檔案。使用 NPM,從 @types/google.maps 套件安裝 Google Maps JavaScript 宣告檔案:
npm i -D @types/google.maps
詳情請參閱 GitHub 上的來源檔案。
將 google.maps 新增至 tsconfig types 選項
如果 tsconfig 檔案設定了 types 編譯器選項,TypeScript 只會包含該陣列中列出的 @types 套件。光是安裝 @types/google.maps,並不足以啟用 Google 地圖的 TypeScript 支援,使用 google 命名空間的程式碼會無法編譯,並顯示下列錯誤:
Error T2503: Cannot find namespace 'google'.
如要將 google.maps 新增至 types 陣列,請按照下列步驟操作:
{
"compilerOptions": {
"types": ["google.maps"]
}
}
或者,您也可以在專案包含的宣告檔案 (例如 vite-env.d.ts) 中加入下列指令:
/// <reference types="google.maps" />
詳情請參閱「類型」。
@type 套件發生衝突
部分程式庫可能會使用 @types/google.maps 以外的套件,因此可能會造成衝突。使用 skipLibCheck 編譯器選項,可避免類型不一致的問題:
{
"compilerOptions": {
"skipLibCheck": true
}
}
指定 typeRoots
部分架構 (例如 Angular) 可能需要指定 typeRoots 編譯器選項,才能納入透過 @types/google.maps 和所有其他 @types 套件安裝的類型。
根據預設,編譯中會包含所有可見的 @types 套件。任何封閉資料夾中 node_modules/@types 的套件都會視為可見:
{
"compilerOptions": {
"typeRoots": [
"node_modules/@types"
]
}
}