25

Heyho,

I want to use some javascript libraries in my typescript code for which there are no typings in npm. So I wrote the typings myself and put them in a definitions directory in my source tree. However, I could not get typescript to look in that directory for those modules.

My directory structure looks like this:

+-node_modules
| |
| +-moduleA
| |
| +-moduleB
|
+-src
| |
| +-definitions
| | |
| | +-moduleA.d.ts
| | |
| | +-moduleB.d.ts
| |
| +-ts
|   |
|   + ... all typescript code ...
|
+-tsconfig.json

I tried including the modules in the definitions-directory using

  • include
  • files
  • typeRoots
  • paths

However none of it worked.

Can somebody tell me, how to get typescript to include those typings?

PS: Why is the TypeScript module handling so complicated???

2 Answers 2

20
{
  "compilerOptions": {
    "typeRoots": [
      "./node_modules/@types",
      "./some-custom-lib"
    ]
  }
}

the typeRoots string array is just for that. In addition to your regular "node_modules/@type", add a custom made typings folder.

5
  • 1
    This seems to work as long as I do not have any import-statements in my module definition. But without the import I cannot type my module correctly.
    – jsf
    Aug 4, 2017 at 13:29
  • This doesn't work because typeRoots expect typings in script format instead of module format.
    – unional
    Aug 4, 2017 at 16:53
  • Is that documented somewhere? I could not find information on such things.
    – jsf
    Aug 9, 2017 at 15:45
  • I have no idea, this is just what I do.
    – qballer
    Aug 10, 2017 at 12:56
  • I found my typeRoots were ignored as I had the files ending with .d.ts ; changing to .ts instead works; so this approach no doubt requires some other compiler options set to not ignore the .d.ts (at least in my case)
    – Dessus
    Jan 19, 2022 at 23:19
8

You can include them with the triple-slash Directives to direct the compiler to use them.

E.g. create an index.d.ts file and put it your definitions folder. There you can include every custom typing you made. It could look like this

/// <reference path="react.patch.d.ts" />
/// <reference path="custom-typings.d.ts" />

Inside the typings file the first line has to be

/// <reference types="nameOfIt" />

Then in your tsconfig.json you include them in the files field e.g.

"files": [
    "definitions/index.d.ts"
  ]

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.