TypeScript ומפות Google

TypeScript הוא קבוצת-על מסוג מוקלדת של JavaScript מה הידור (compile) ל-JavaScript פשוט. קטע הקוד הבא מדגים שימוש פשוט במפות Google באמצעות 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
  });
}

תחילת העבודה

הפרויקט DefinitelyTyped הוא פרויקט בקוד פתוח שבו נשמרים סוג קובצי הצהרה של חבילות רבות, כולל מפות Google. אפשר להתקין את קובצי הצהרת ה-JavaScript של מפות Google (ראו קובצי מקור ב-GitHub) באמצעות NPM מהחבילה @types/google.maps.

npm i -D @types/google.maps

תכונות אלפא ובטא

לסוגים בדרך כלל אין את המאפיינים, הפונקציות והמחלקות שנמצאים בגרסאות אלפא או בטא. ברבים מהמקרים האלה, אפשר להמיר את האובייקט לסוג הנכון.

השגיאה הבאה נגרמת על ידי נכס הבטא mapId של 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'.

אפשר לתקן את השגיאה שלמעלה על ידי הפעלת Cast שלמטה.

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

חבילות @types מתנגשות

ספריות מסוימות עשויות להשתמש בחבילה אחרת מלבד @types/google.maps, שעלולה לגרום להתנגשויות. השתמשו באפשרות המהדר skipLibCheck כדי למנוע בעיות עם סוגים לא עקביים.

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

ציון typeRoots

ב-frameworks מסוימות, כמו Angular, יכול להיות שיהיה צורך לציין את אפשרות המהדר (compiler) typeRoots כדי לכלול סוגים שהותקנו מ-@types/google.maps ומכל החבילות האחרות של @types.

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