TypeScript คือชุดซูเปอร์ของ 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 อาจต้องระบุตัวเลือกคอมไพเลอร์ typetypes เพื่อรวมประเภทที่ติดตั้งจาก @types/google.maps และแพ็กเกจ "@types" อื่นๆ ทั้งหมด
{
...
"compilerOptions": {
...
"typeRoots": [
"node_modules/@types",
],
...
}
}