64

I am setting a web app up in TypeScript and I seem to be missing some basic types I need.

When I compile (npm run build), I get the following errors,

error TS2304: Cannot find name 'HTMLElement'.

error TS2304: Cannot find name 'SVGElement'.

error TS2304: Cannot find name 'EventTarget'.

error TS2304: Cannot find name 'TouchEvent'.

error TS2304: Cannot find name 'MouseEvent'.

error TS2304: Cannot find name 'PointerEvent'.

Based on my Googling I assuming I am missing something basic in my project setup. It seems like these types are just assumed to be there with Typescript.

EDIT: Specially it should be part of the ES6 types, https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.d.ts.

Here is my package.json file:

{
  "name": "wip",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "dependencies": {
    "hammerjs": "2.0.8"
  },
  "devDependencies": {
    "@types/chai": "3.4.35",
    "@types/mocha": "2.2.39",
    "@types/node": "7.0.5",
    "@types/hammerjs": "2.0.34",
    "chai": "3.5.0",
    "mocha": "3.2.0",
    "safe-mock": "0.2.0",
    "ts-node": "2.1.0",
    "tslint": "4.5.1",
    "typescript": "2.2.1",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  },
  "scripts": {
    "test": "mocha test --require ts-node/register test/**/*.ts && npm run build",
    "dev": "webpack-dev-server --watch --content-base . -d --progress",
    "build": "tsc"
  },
  "author": "",
  "license": "ISC"
}

Any suggestions?

Community
  • 1
  • 1
James McMahon
  • 48,506
  • 64
  • 207
  • 283

2 Answers2

124

Try adding the following lib section to your tsconfig.json file.

{
    "compilerOptions": {
        "lib": [
            "es2016",
            "dom"
        ]
    }
}
Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • 2
    Fix it, thanks! Though I use `es6` instead of `es2016`. Strange that I needed to do that because I had the type in my `node_modules` directory. – James McMahon Mar 05 '17 at 03:15
  • 1
    This is the correct solution, currently, but beware of this. Your build will not fail if you use a variable 'event' that is not defined in that file, because lib.dom.d.ts is declaring 'event' as well as a number of other very common variable names. – SgtPooki May 31 '18 at 19:00
  • [It didn't work for me, sadly](https://stackoverflow.com/q/74035705/4756173) :/ – Philippe Fanaro Oct 12 '22 at 02:00
  • this doesn't work on an nx workspace – Philip Mutua Dec 18 '22 at 11:24
2

Additional answer for testing.

If using mocha, you also need to tell mocha about the DOM environment using jsdom.

https://journal.artfuldev.com/unit-testing-node-applications-with-typescript-using-mocha-and-chai-384ef05f32b2

$ npm install jsdom jsdom-global --save-dev

So your "test" script would add -r jsdom-global/register:

{
  "scripts": {
    "test": "mocha test -r ts-node/register -r jsdom-global/register test/**/*.ts && npm run build"
  }
}
Xeoncross
  • 55,620
  • 80
  • 262
  • 364