TypeScript และ Google Maps

TypeScript คือ Superset ของ JavaScript ที่มีการพิมพ์ ที่คอมไพล์เป็น JavaScript ธรรมดา ข้อมูลโค้ดด้านล่างแสดงการใช้งานที่เรียบง่าย ของ Google Maps โดยใช้ 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 Maps การประกาศ JavaScript ของ Google Maps (โปรดดู ไฟล์ต้นฉบับ บน 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'.

ข้อผิดพลาดข้างต้นแก้ไขได้ด้วยการแคสต์ที่ด้านล่าง

{ 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 และ "@type" อื่นๆ ทั้งหมด แพ็กเกจของคุณ

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