Types from lib.dom.d.ts not found when building

Viewed 5577

I have the following simple constructor function:

constructor() {
    const myTextAlign: CanvasTextAlign = 'center';
    const myHTMLDoc: HTMLDocument = null;
    console.log(myTextAlign);
}

VS Code reports no issues with the code, and if I click on CanvasTextAlign or HTMLDocument and press F12 it correctly takes me to the lib.dom.d.ts. However when I try to run ng build the Angular compiler throws the following error:

error TS2304: Cannot find name 'CanvasTextAlign'.

It never reports an error about the HTMLDocument so it seems it can find some definitions in the lib.dom.d.ts but not all of them.

tsconfig.json looks like this:

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

The tsconfig.app.json looks like this:

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

Both json files are vanilla versions that were created when ng new was run

1 Answers

You have to tell angular, which CanvasTextAlign you mean.

Use something like this, at the top of your controller ts file:

import {CanvasTextAlign} from 'mylibrary';

And make sure, that this libary is in your node_modules directory.

HTMLDocument on the other hand does not need such an import, it is part of angular itself.

Related