reactjs - Typescript Lỗi: Khai báo module ambient chỉ được phép ở cấp cao nhất trong một tệp
Hiện tại đang cố gắng lấy dữ liệu từ một dịch vụ của Google. Tôi không chắc mình nên xử lý lỗi này như thế nào khi khai báo global.
Liên kết đến đoạn mã gốc: https://stackblitz.com/edit/github-mge1vg?file=index.ts
Làm thế nào tôi có thể giải quyết điều này và tại sao tôi lại nhận được lỗi.
Phần mã này gây ra lỗi:
An ambient module declaration is only allowed at the top level in a file. declare global {
interface Window {
initMap: () => void;
}
}
window.initMap = initMap;
Đây là toàn bộ mã:
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;
};
Câu trả lời #1
Chuyển động
declare global {
interface Window {
initMap: () => void;
}
}
Bên ngoài hàm chính hoạt động, sau đó gọi
const initMap = () => {
const geocoder = new google.maps.Geocoder();
setGeocoder(geocoder);
};
window.initMap = initMap;
Trong tệp, bạn sẽ sử dụng hook và thêm thẻ script để khởi tạo API của Google
<script
src={`https://maps.googleapis.com/maps/api/js?key=${your API key}&callback=initMap&v=weekly&libraries=geocoder`}
defer
></script>
