Search code examples
typescriptgoogle-mapsbuildreact-app-rewired

typescript error using google.maps - 'google' is not defined


I have the following in package.json

"@types/google.maps": "~3.48.3",

// in my tsx file the first line at the top is

/// <reference types='google.maps' />

But on accessing google.maps.MapMouseEvent - I get the error 'google' is not defined. Line 980:43: 'google' is not defined no-undef

Line 980 is

onMarkerDragEnd = async (mapMouseEvent: google.maps.MapMouseEvent) => {

// I also tried

/// <reference path='../../../../node_modules/@types/google.maps' />

// I also tried in tsconfig.json

  "compilerOptions": {
    "types": [
      "google.maps"
    ]
  }

But the error persists. I am compiling the typescript using

react-app-rewired build

Looking for any tips on how to use the @types/google.maps in typescript.


Solution

  • no-undef is actually an eslint error which can be fixed with https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals

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

    With recent versions of typescript you shouldn't need anything other than the following in your package.json.

      devDependencies: {"@types/google.maps": ...}
    

    Install with:

    npm install -D @types/google.maps
    

    No triple slash reference, no imports, no compilerOptions.types.

    See https://codesandbox.io/embed/github/googlemaps/js-samples/tree/sample-marker-simple for an example.