TypeScript 및 Google 지도

TypeScript는 일반 자바스크립트로 컴파일되는 자바스크립트 유형의 상위 집합입니다. 아래 스니펫은 TypeScript를 사용한 Google 지도의 간단한 사용 예를 보여줍니다.

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 지도를 비롯한 많은 패키지의 선언 파일 유형을 유지 관리하는 오픈소스 프로젝트입니다. Google Maps 자바스크립트 선언 파일(GitHub의 소스 파일 참고)은 @types/google.maps 패키지의 NPM을 사용하여 설치할 수 있습니다.

npm i -D @types/google.maps

알파 및 베타 기능

유형에는 일반적으로 알파 또는 베타 버전의 속성, 함수 또는 클래스가 포함되지 않습니다. 이러한 경우 대부분 객체를 올바른 유형으로 캐스팅할 수 있습니다.

다음 오류는 MapOptionsmapId 베타 속성으로 인해 발생합니다.

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",
        ],
        ...
    }
}