'Typescript Error: An ambient module declaration is only allowed at the top level in a file

Currently trying to fetch data from a google service. I'm not sure how I should handle this error when declaring global.

Link to the original code snippet:https://stackblitz.com/edit/github-mge1vg?file=index.ts

How would solve this and why am I getting the error.
This part of the code throws an error:

An ambient module declaration is only allowed at the top level in a file.

 declare global {
    interface Window {
      initMap: () => void;
    }
  }
  window.initMap = initMap;

Here is the whole code:

import {useEffect, useState} from 'react';

type Geocode = {
  data?: google.maps.GeocoderResult | null;
  loading: boolean;
  error: string | null;
};

export const useReverseGeoCoding = ({latitude, longitude}: {latitude: number; longitude: number}): Geocode => {
  const [geocode, setGeocode] = useState<Geocode>({loading: false, error: null});

  useEffect(() => {
    const geocodeLatLng = async (geocoder: google.maps.Geocoder) => {
      /// Hard Coded for now
      const latlng = {
        lat: 52.509865,
        lng: -0.118092,
      };

      geocoder
        .geocode({location: latlng})
        .then(response => {
          if (response.results[0]) {
            console.log('response:', response);
            setGeocode({data: response.results[0], loading: false, error: null});
          } else {
            console.log('No results found');
          }
        })
        .catch(error => console.log('Geocoder failed due to: ' + error));
    };
    const initMap = (): void => {
      const geocoder = new google.maps.Geocoder();
      geocodeLatLng(geocoder);
    };
    initMap();
  }, [latitude, longitude]);

  declare global {
    interface Window {
      initMap: () => void;
    }
  }
  window.initMap = initMap;

  return geocode;
};


Solution 1:[1]

Moving

declare global {
  interface Window {
    initMap: () => void;
  }
}

Outside of the main function works, then calling

  const initMap = () => {
    const geocoder = new google.maps.Geocoder();
    setGeocoder(geocoder);
  };
  window.initMap = initMap;

Within the file you will use the hook, and add a script tag to initialize the Google API

 <script
      src={`https://maps.googleapis.com/maps/api/js?key=${your API key}&callback=initMap&v=weekly&libraries=geocoder`}
      defer
    ></script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vash