Angular 6 application cannot find namespace 'google'

Murphy4 picture Murphy4 · Aug 3, 2018 · Viewed 20.8k times · Source

This question has appeared similarly in many places where the solution is to simply add

import { } from '@types/googlemaps';

which worked as a solution in past versions of angular. The issue appeared now that I am using Angular 6+

TS2304: Cannot find name 'google'.
TS2503: Cannot find namespace 'google'.

There are numerous errors like this anywhere I use google maps types. For example:

let place: google.maps.places.PlaceResult = autocomplete.getPlace();

I can quickfix the issue by inserting // @ts-ignore above all lines that use google maps, but I am much more interested in a true fix. But the fact this works makes me feel it's a tsconfig issue which I am not super confident about.

I can confirm that googlemaps is installed inside node_modules/@types, but I am not sure about the tsconfig

ts.config

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "typeRoots": [
      "node_modules/@types",
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

I created a Stackblitz Example which throws a Reference Error if you view the console. I don't know what to try next.

Answer

Vaibhav Kumar Goyal picture Vaibhav Kumar Goyal · Aug 3, 2018

So I came across the problem earlier on GitHub and this worked for me:

  • npm install --save-dev @types/googlemaps

  • Adding to all my tsconfig*.json: types: [ "googlemaps"]

  • Adding at the top of my file: declare const google: any;

  • Adding at the end of the body of my index.html:

    <script async defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=****"> </script>

Try it out and tell me whether it works.