TypeScript React Google Maps: 'google' does not exist

Viewed 2055

I have loaded the google maps Javascript API in the public/index.html and in dev tools console I can log window.google.maps just fine.

enter image description here

But TypeScript doesn't know its there and I get this error Property 'google' does not exist on type 'Window & typeof globalThis'.ts(2339) How do I tell typescript it does exist?

import React, { useRef } from "react";

function Map() {
    const mapRef = useRef<HTMLDivElement>(null);
    const google = window.google;
//                          ^ Error: Property 'google' does not exist on type 'Window & typeof globalThis'
    const myLatlng = new google.maps.LatLng(-34.397, 150.644);
    const mapOptions = {
    zoom: 8,
    center: myLatlng,
    };
    const map = new google.maps.Map(mapRef.current, mapOptions);
  return (<div ref={mapRef}></div>);
}

export { Map };
2 Answers

I thought about this some more. If you have not installed the Google Map typings from DefinitelyTyped, I suggest doing so:

npm install --save @types/googlemaps. (Or --save-dev if you only want them for your own development.)

Related