[英]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
.我不确定在声明
global
时应该如何处理这个错误。
Link to the original code snippet: https://stackblitz.com/edit/github-mge1vg?file=index.ts链接到原始代码片段: 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;
};
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在文件中,您将使用钩子,并添加一个脚本标签来初始化 Google API
<script
src={`https://maps.googleapis.com/maps/api/js?key=${your API key}&callback=initMap&v=weekly&libraries=geocoder`}
defer
></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.