James Moorhouse James Moorhouse - 1 month ago 20
TypeScript Question

Typescript 2 can't find custom definitions

I'm trying to use some external js libraries from NPM with my typescript project, unfortunately these libraries don't have @types definitions provided so I've taken to writing my own. The definitions I've written work when I nest them in

./node_modules/@types/<library_name>/*.d.ts
but as soon as I move them to e.g.
./@types/<library_name>/*.d.ts
they don't get picked up by the compiler and I get the following error:

ERROR in ./utils/eventEmitter.ts
(1,25): error TS2307: Cannot find module 'events'.


I'm using: TypeScript Version: 2.0.3 from npm

I've got the following project structure setup

@types/
-- events
---- index.d.ts
node_modules/
-- @types
-----react, react-dom etc
utils/
-- eventEmitter.js
tsconfig.json


In my tsconfig.json I have:

{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"target": "es5",
"jsx": "react",
"allowJs": true,
"sourceMap": true,
"typeRoots" : [
"./@types"
],
"types" : [
"events",
"ajax",
"path",
"keymirror"
]
},
"exclude" : [
"node_modules",
"@types"
]
}


in eventEmitter.js I have the following:

import * as events from "events";


Just to clarify the concrete events module JS is located at
./node_modules/events/index.js

Answer

The problem described by my question has been acknowledged as a bug in typescript (I'm using 2.0.3).

The solution is to add the following config to tsconfig.json:

{
"compilerOptions": {
    ...
    "path": {
         "*": ["*", "./@types/*"]
     }
     ...
  }
}

as per: github issue