TypeScript เป็นชุด JavaScript ขั้นสูงที่คอมไพล์เป็น 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
});
}
เริ่มต้นใช้งาน
โปรเจ็กต์ De specificTyped เป็นโปรเจ็กต์โอเพนซอร์สที่เก็บรักษาประเภทไฟล์ประกาศสำหรับแพ็กเกจจำนวนมาก รวมถึง Google Maps ไฟล์ประกาศ Google Maps JavaScript (ดูไฟล์ต้นฉบับบน 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 และแพ็กเกจ "@types" อื่นๆ ทั้งหมดด้วย
{
...
"compilerOptions": {
...
"typeRoots": [
"node_modules/@types",
],
...
}
}