1
votes

I'm trying to use Google Charts in an Angular CLI (7.2.3) project but am running into an issue getting the typings to work.

First, I installed the typings with this command (both with and without the -dev flag):

npm install --save-dev @types/google.visualization

After doing this, intellisense starts working immediately in Visual Studio Code and I don't get any highlighted errors when I create a simple test like this:

const chartBoxStyle: google.visualization.ChartBoxStyle = {};

However, when I try to build by running ng build, I get this error:

error TS2503: Cannot find namespace 'google'.

I have tried adding this to my file with no luck:

declare const google: any;

My tsconfig.json file has the following for typeRoots and I see the google.visualization folder in there:

"typeRoots": ["node_modules/@types"]

Any help would be greatly appreciated as I'm out of ideas on how to progress past this.

1
To create your project, did you run ng new my-app? - Shaun Luttin

1 Answers

4
votes

Summary

The problem is the "types" property in the ./src/tsconfig.app.json file.

Even though the root ./tsconfig.json file sets "typeRoots" to ["node_modules/@types"], the ./src/tsconfig.app.json file disables inclusion of those types by setting its own types property to an empty array.

Solution

Open ./src/tsconfig.app.json and make one of two changes:

  • Delete the "types": []" property; that will tell the compiler to include all typeRoots packages.

  • Alternatively, add the types that you want to use into the "types": []" array.

The latter option would look like this:

"types": [
  "google.visualization"
]

Details

ng build reads its configuration from the ./angular.json file.

That ./angular.json file sets "tsConfig" to "src/tsconfig.app.json".

That ./src/tsconfig.app.json file sets its "types" property to an empty array.

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": []  <------------------------------- empty array
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

That's the problem, because as the TypeScript documentation says: "If types is specified, only packages listed will be included."