Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 application cannot find namespace 'google'

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.

like image 410
Murphy4 Avatar asked Aug 03 '18 17:08

Murphy4


3 Answers

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.

like image 173
Vaibhav Kumar Goyal Avatar answered Nov 18 '22 18:11

Vaibhav Kumar Goyal


The tsconfig.json file that really needs to be updated is in src/tsconfig.app.json.

That files overrides the types property of compilerOptions of the tsconfig.json file in the root directory with an empty array so you must add the types definition for googlemaps there.

For example:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["googlemaps"]
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}
like image 21
Robert Tamlyn Avatar answered Nov 18 '22 18:11

Robert Tamlyn


Adding it to the types array of my tsconfig compiler options has never worked. But if you have the @types/googlemaps installed, you can reference this at the top of your .ts file using:

/// <reference types="@types/googlemaps" />

cf. Triple Slash Directives

like image 8
Martyn Verhaegen Avatar answered Nov 18 '22 17:11

Martyn Verhaegen