Typescript eslint מסמן ש-'google' אינו מוגדר עבור google.maps.Marker[]


const google = window.google;
        let markers: google.maps.Marker[] = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener("places_changed", () => {
            const places = searchBox.getPlaces();

            if (places.length === 0) {
                return;
            }

            // Clear out the old markers.
            markers.forEach((marker) => {
                marker.setMap(null);
            });
            markers = [];

            // For each place, get the icon, name and location.
            const bounds = new google.maps.LatLngBounds();
            places.forEach((place) => {
                if (!place.geometry || !place.geometry.location) {
                    return;
                }
                const icon = {
                    url: place.icon as string,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25),
                };

                // Create a marker for each place.
                markers.push(
                    new google.maps.Marker({
                        map,
                        icon,
                        title: place.name,
                        position: place.geometry.location,
                    })
                );

                if (place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
            });
            map.fitBounds(bounds);
        });

זה קצת קוד מ-API של Google Maps. זה מתכנס ופועל מצוין.

הבעיה היא שכאשר כלי בדיקת קוד בודק את זה, הוא נותן לי את השגיאה הזו: 222:22 error 'google' לא מוגדר no-undef

הוספתי const google=window.google; לחלק העליון של הקוד כפי שהתשובה הזו מסבירה. google לא מוגדר באפליקציית react שמשתמשת ב-create-react-app

אבל זה עוזר רק במקרים שבהם נעשה שימוש במילת המפתח 'new'.

זה לא עזר במקרה הזה let markers: google.maps.Marker[]=[]; שבו סוג מוקצה למשתנה.

תשובה #1

עם eslint, אתה יכול להגדיר גלובלי. https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals

{
    "globals": {
        "google": "readonly"
    }
}